nandi/rustnimpublic Fork 0
d4592812fae6b652d94be442f5b3a408d3ab21b6
Commits
Clone
git clone https://git.rickub.com/nandi/rustnim.git
git clone ssh://git@rickub.com/nandi/rustnim.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Expand multi-rule and recursive macro_rules d459281 · on d4592812fae6b652d94be442f5b3a408d3ab21b6 · nandithebull · 7h ago
039-macro-multi-rule.rs · 44 lines · 1.2 KBRust Blame HistoryRaw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Rules are tried top to bottom and the first whose matcher matches wins, so
// their order is semantics rather than style. That is also what makes a
// recursive macro terminate: a base-case rule sits above the recursive one.

macro_rules! describe {
    () => { 0 };
    ($x:expr) => { $x };
    ($x:expr, $y:expr) => { $x * 100 + $y };
}

// Recursion, shedding one argument per step.
macro_rules! total {
    () => { 0 };
    ($x:expr) => { $x };
    ($x:expr, $($rest:expr),+) => { $x + total!($($rest),+) };
}

macro_rules! depth {
    ($x:expr) => { 1 };
    ($x:expr, $($rest:expr),+) => { 1 + depth!($($rest),+) };
}

// Different shapes, not just different arities.
macro_rules! pick {
    (first $a:expr, $b:expr) => { $a };
    (second $a:expr, $b:expr) => { $b };
    (sum $a:expr, $b:expr) => { $a + $b };
}

fn main() {
    println!("{} {} {}", describe!(), describe!(7), describe!(3, 4));

    println!("{}", total!());
    println!("{}", total!(5));
    println!("{}", total!(1, 2, 3, 4, 5));
    println!("{}", total!(2 * 3, 4 + 1));

    println!("{} {}", depth!(9), depth!(9, 9, 9, 9));

    println!("{} {} {}", pick!(first 10, 20), pick!(second 10, 20), pick!(sum 10, 20));

    let a: i64 = 1000;
    println!("{}", total!(a, a, a));
}