nandi/rustnimpublic Fork 0
main
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.

039-macro-multi-rule.rs · 44 lines · 1.2 KBRust Blame HistoryRaw
Expand multi-rule and recursive macro_rules d459281 nandithebull 9h ago1// Rules are tried top to bottom and the first whose matcher matches wins, so
2// their order is semantics rather than style. That is also what makes a
3// recursive macro terminate: a base-case rule sits above the recursive one.
4
5macro_rules! describe {
6 () => { 0 };
7 ($x:expr) => { $x };
8 ($x:expr, $y:expr) => { $x * 100 + $y };
9}
10
11// Recursion, shedding one argument per step.
12macro_rules! total {
13 () => { 0 };
14 ($x:expr) => { $x };
15 ($x:expr, $($rest:expr),+) => { $x + total!($($rest),+) };
16}
17
18macro_rules! depth {
19 ($x:expr) => { 1 };
20 ($x:expr, $($rest:expr),+) => { 1 + depth!($($rest),+) };
21}
22
23// Different shapes, not just different arities.
24macro_rules! pick {
25 (first $a:expr, $b:expr) => { $a };
26 (second $a:expr, $b:expr) => { $b };
27 (sum $a:expr, $b:expr) => { $a + $b };
28}
29
30fn main() {
31 println!("{} {} {}", describe!(), describe!(7), describe!(3, 4));
32
33 println!("{}", total!());
34 println!("{}", total!(5));
35 println!("{}", total!(1, 2, 3, 4, 5));
36 println!("{}", total!(2 * 3, 4 + 1));
37
38 println!("{} {}", depth!(9), depth!(9, 9, 9, 9));
39
40 println!("{} {} {}", pick!(first 10, 20), pick!(second 10, 20), pick!(sum 10, 20));
41
42 let a: i64 = 1000;
43 println!("{}", total!(a, a, a));
44}