adding macro examples

This commit is contained in:
aj 2020-10-11 11:37:12 +01:00
parent 4ff6d69534
commit c1e100650c
2 changed files with 36 additions and 0 deletions

32
src/macros.rs Normal file
View File

@ -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),+))
)
}

View File

@ -3,6 +3,7 @@ use std::cmp::Ordering;
use rand::Rng; use rand::Rng;
mod iterate; mod iterate;
mod macros;
fn main() { fn main() {
basics(); basics();
@ -17,6 +18,9 @@ fn main() {
} }
fn basics() { fn basics() {
println!("min: {}", find_min!(5, 6));
// ! indicates a macro not a func // ! indicates a macro not a func
println!("Enter a number: "); println!("Enter a number: ");