简体   繁体   English

在Rust中声明变量的宏?

[英]Macro that declare variables in Rust?

In C its possible to write a macro that declares variables, as follows: 在C中可以编写一个声明变量的宏,如下所示:

#define VARS(a, b, c) \
    int a, b, c;

Of course this isn't something you'd typically want to do. 当然,这不是您通常想要执行的操作。

In the actual example I'm looking to get working its not quite so simple. 在实际示例中,我希望使其工作起来不是那么简单。

#define VARS(data, stride, a, b, c) \
    MyStruct *a = &data.array[0],            \
    MyStruct *b = &data.array[1 * (stride)], \
    MyStruct *c = &data.array[2 * (stride)];

However the exact details of assignment shouldn't matter for the purpose of this question. 但是,对于这个问题,确切的分配细节并不重要。

Is it possible to write a macro like this in Rust? 是否可以在Rust中编写这样的宏? If so how would this be written? 如果是这样,如何写?

It is possible to write such a macro in Rust: 可以在Rust中编写这样的宏:

macro_rules! vars {
    ($data:expr, $stride:expr, $var1:ident, $var2:ident, $var3:ident) => {
        let $var1 = $data[0];
        let $var2 = $data[1 * $stride];
        let $var3 = $data[2 * $stride];
    };
}

fn main() {
    let array = [1, 2, 3, 4, 5];
    let stride = 2;
    vars!(array, stride, a, b, c);
    println!("{}", a);
    println!("{}", b);
    println!("{}", c);
}

Read the Macros chapter in the book for more information. 阅读本书中的“宏”一章以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM