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 `$(..)` repetition in macro_rules 3d4a7d2 · on d4592812fae6b652d94be442f5b3a408d3ab21b6 · nandithebull · 7h ago
038-macro-repetition.rs · 46 lines · 1.1 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
45
46
// `$(..)` repetition — 28% of the `macro_rules!` in a 400-crate sample. The
// matcher binds each fragment once per iteration, and the transcriber emits
// its body once per iteration, joined by the separator.

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

macro_rules! max_of {
    ($first:expr $(, $rest:expr)*) => {{
        let mut m = $first;
        $( if $rest > m { m = $rest; } )*
        m
    }};
}

macro_rules! count_args {
    ($($x:expr),*) => {
        0 $(+ { let _ = $x; 1 })*
    };
}

macro_rules! pairs_sum {
    ($($a:expr => $b:expr),*) => {
        0 $(+ $a * $b)*
    };
}

fn main() {
    println!("{}", sum_all!());
    println!("{}", sum_all!(1));
    println!("{}", sum_all!(1, 2, 3, 4));
    // Precedence survives: each capture is parenthesised.
    println!("{}", sum_all!(1 + 1, 2 * 3));

    println!("{}", max_of!(3));
    println!("{}", max_of!(3, 9, 2));
    println!("{}", max_of!(-5, -9, -1));

    println!("{}", count_args!(7, 8, 9));
    println!("{}", count_args!());

    println!("{}", pairs_sum!(2 => 3, 4 => 5));
}