简体   繁体   中英

Macro that declare variables in Rust?

In C its possible to write a macro that declares variables, as follows:

#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? If so how would this be written?

It is possible to write such a macro in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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