首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Rust中实现post增量宏

如何在Rust中实现post增量宏
EN

Stack Overflow用户
提问于 2019-12-29 18:44:32
回答 1查看 184关注 0票数 0

在Rust中实现后增量宏是可能的吗?

代码语言:javascript
复制
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
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-29 19:06:13

是!这很简单:

代码语言:javascript
复制
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)

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59518695

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档