在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
}发布于 2019-12-29 19:06:13
是!这很简单:
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
}https://stackoverflow.com/questions/59518695
复制相似问题