是否可以在 Rust 中实现后增量宏?
fn main() {
let mut i = 0usize;
let v = vec!(0,1,2,3,);
println!("{}", post_inc!(i)); // 0
println!("{}", post_inc!(i)); // 1
// i = 3
}
Run Code Online (Sandbox Code Playgroud)
是的!这很容易:
macro_rules! post_inc {
($i:ident) => { // the macro is callable with any identifier (eg. a variable)
{ // the macro evaluates to a block expression
let old = $i; // save the old value
$i += 1; // increment the argument
old // the value of the block is `old`
}
};
}
fn main() {
let mut i = 0usize;
let v = vec![0, 1, 2, 3];
println!("{}", post_inc!(i)); // 0
println!("{}", post_inc!(i)); // 1
// i = 3
}
Run Code Online (Sandbox Code Playgroud)