是否可以在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
}
最佳答案
是的!这很简单:
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
}
(Permalink to the playground)
关于rust - 如何在Rust中实现后增量宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59518695/