From c1e100650cf53d938b9e086f389a42c4c56ee13b Mon Sep 17 00:00:00 2001 From: aj Date: Sun, 11 Oct 2020 11:37:12 +0100 Subject: [PATCH] adding macro examples --- src/macros.rs | 32 ++++++++++++++++++++++++++++++++ src/main.rs | 4 ++++ 2 files changed, 36 insertions(+) create mode 100644 src/macros.rs diff --git a/src/macros.rs b/src/macros.rs new file mode 100644 index 0000000..4d48019 --- /dev/null +++ b/src/macros.rs @@ -0,0 +1,32 @@ + +#[macro_export] +macro_rules! log { + ( $( $t:tt )* ) => { + web_sys::console::log_1(&format!( $( $t )* ).into()); + } +} + +#[macro_export] +macro_rules! expr_stringer { + // This macro takes an expression of type `expr` and prints + // it as a string along with its result. + // The `expr` designator is used for expressions. + ($expression:expr) => { + // `stringify!` will convert the expression *as it is* into a string. + format!("{:?} = {:?}", stringify!($expression), $expression) + }; + ($expression:literal) => { + format!("{:?} = {:?}", $expression, "Nothing") + }; +} + +#[macro_export] +macro_rules! find_min { + // Base case: + ($x:expr) => ($x); + // `$x` followed by at least one `$y,` + ($x:expr, $($y:expr),+) => ( + // Call `find_min!` on the tail `$y` + std::cmp::min($x, find_min!($($y),+)) + ) +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index eb5e2ab..34611e9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,7 @@ use std::cmp::Ordering; use rand::Rng; mod iterate; +mod macros; fn main() { basics(); @@ -17,6 +18,9 @@ fn main() { } fn basics() { + + println!("min: {}", find_min!(5, 6)); + // ! indicates a macro not a func println!("Enter a number: ");