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.

038-macro-repetition.rs · 46 lines · 1.1 KBRust Blame HistoryRaw
Expand `$(..)` repetition in macro_rules 3d4a7d2 nandithebull 8h ago1// `$(..)` repetition — 28% of the `macro_rules!` in a 400-crate sample. The
2// matcher binds each fragment once per iteration, and the transcriber emits
3// its body once per iteration, joined by the separator.
4
5macro_rules! sum_all {
6 ($($x:expr),*) => {
7 0 $(+ $x)*
8 };
9}
10
11macro_rules! max_of {
12 ($first:expr $(, $rest:expr)*) => {{
13 let mut m = $first;
14 $( if $rest > m { m = $rest; } )*
15 m
16 }};
17}
18
19macro_rules! count_args {
20 ($($x:expr),*) => {
21 0 $(+ { let _ = $x; 1 })*
22 };
23}
24
25macro_rules! pairs_sum {
26 ($($a:expr => $b:expr),*) => {
27 0 $(+ $a * $b)*
28 };
29}
30
31fn main() {
32 println!("{}", sum_all!());
33 println!("{}", sum_all!(1));
34 println!("{}", sum_all!(1, 2, 3, 4));
35 // Precedence survives: each capture is parenthesised.
36 println!("{}", sum_all!(1 + 1, 2 * 3));
37
38 println!("{}", max_of!(3));
39 println!("{}", max_of!(3, 9, 2));
40 println!("{}", max_of!(-5, -9, -1));
41
42 println!("{}", count_args!(7, 8, 9));
43 println!("{}", count_args!());
44
45 println!("{}", pairs_sum!(2 => 3, 4 => 5));
46}