gpt4 book ai didi

rust - 如何在Rust中实现后增量宏

转载 作者:行者123 更新时间:2023-12-03 11:40:55 25 4
gpt4 key购买 nike

是否可以在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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com