adding macro examples
This commit is contained in:
parent
4ff6d69534
commit
c1e100650c
32
src/macros.rs
Normal file
32
src/macros.rs
Normal 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),+))
|
||||
)
|
||||
}
|
@ -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: ");
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user