macro_rules! is {
($cond:expr ; $then:expr) => { ... };
($cond:expr ; $then:expr ; $($else:expr)?) => { ... };
(let $pat:pat = $cond:expr ; $then:expr) => { ... };
(let $pat:pat = $cond:expr ; $then:expr ; $($else:expr)? ) => { ... };
(tmp $name:pat = $val:expr; $($rest:tt)+) => { ... };
($($rest:tt)+) => { ... };
}
Expand description
Conditional evaluation.
Combines:
if
/else
conditionsif let
pattern matching- Temporary value binding
ยงExamples
- Replacing
if
:
is![true; print!("true")];
// This
let s = is![1 > 0; true; false];
// Would be equivalent to
let s = if 1 > 0 {
true
} else {
false
};
- Replacing
if let
:
let num = Some(123);
// This
is![let Some(n) = num ; println!("num:{n}") ; { dbg![num]; }];
// Would be equivalent to
if let Some(n) = num {
println!("num:{n}")
} else {
dbg![num];
}
Nested:
let mut s = String::new();
let is_premium = Some(true);
// This
is![let Some(b) = is_premium; is![b; s += " [premium]"]];
// Would be equivalent to
if let Some(b) = is_premium {
if b {
s += " [premium]";
}
}
- Temporary value binding:
let mut s = String::new();
let (a, b) = (1, 2);
// This
is![
tmp A = format_args!("A{a}");
tmp B = format_args!("B{b}");
write!(s, "{A}+{B},");
];
assert_eq![&s, "A1+B2,"];
// Would be equivalent to
match format_args!("A{a}") {
A => match format_args!("B{b}") {
B => { write!(s, "{A}+{B},"); }
}
}
Otherwise it fails with E0716: temporary value dropped while borrowed
(in stable):
โ
let mut s = String::new();
let (a, b) = (1, 2);
let A = format_args!("A{a}"); // โ freed here
let B = format_args!("B{b}"); // โ freed here
write!(s, "{A}+{B},");