本文介绍了在Rust中声明变量的宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C语言中可以编写一个声明变量的宏,如下所示:
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.
是否可以在Rust中编写这样的宏?如果是这样,怎么写?
Is it possible to write a macro like this in Rust?If so how would this be written?
推荐答案
可以在Rust中编写这样的宏:
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);
}
阅读书中的宏章节以获取更多信息.
这篇关于在Rust中声明变量的宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!