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

标签 rust

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

相关文章:

generics - 解析数字的通用函数因 "FromStr is not implemented"而失败

windows - 如何将OsString传递给Win32 API调用

rust - 如何访问 `if let` 表达式之外的变量?

rust - 如何在 Rust 中使用 BigInt 和 Bigint 生成一系列值?

rust - Rust 中的复制语义真的变成了内存中的副本吗?

c# - 如何在 Rust 中并行创建一个数组并将其返回给 C#?

pointers - 我应该如何决定何时更适合或不适合使用原始指针?

rust - 在 Rust 中如何修改文件的内容而不是添加到文件中?

rust - 如何用预定义的容量填充向量?

rust - 如何从Reverse()中获取值?