如何在宏中设置编译时条件
How to set a compile time condition in macros
我想在宏生成函数外代码时设置编译时条件。我需要这样的东西:
macro_rules! cond {
( $cond_el:expr ) => {
#[if $cond_el == "i32"]
struct A {
x: i32
}
#[else]
struct A {
x: f64
}
}
}
cond!("i32");
cond!("f64");
fn main() {}
或者类似的东西:
macro_rules! cond {
( $cond_el:expr ) => {
match $cond_el {
"i32" => {
struct A {
x: i32
}
}
_ => {
struct A {
x: f64
}
}
}
}
}
cond!("i32");
cond!("f64");
fn main() {}
当前的 Rust 宏状态是否可行?
你要求的是不可能的。值得庆幸的是,您的要求和您的示例 表明您想要的 是两件不同的事情:
macro_rules! cond {
("i32") => {
struct A {
x: i32,
}
};
($el:expr) => {
struct B {
x: f64
}
};
}
cond!("i32");
cond!("f64");
fn main() {}
然而,从字面上理解你的问题:不,没有办法对宏中的条件进行任何类型的复杂测试,宏也不能设置或测试传递给它们的内容之外的任何类型的状态。您可以对宏的直接输入进行字面匹配,或者您可以将某些输入解析为有限数量的语法结构之一(然后您无法与之匹配),仅此而已。
我想在宏生成函数外代码时设置编译时条件。我需要这样的东西:
macro_rules! cond {
( $cond_el:expr ) => {
#[if $cond_el == "i32"]
struct A {
x: i32
}
#[else]
struct A {
x: f64
}
}
}
cond!("i32");
cond!("f64");
fn main() {}
或者类似的东西:
macro_rules! cond {
( $cond_el:expr ) => {
match $cond_el {
"i32" => {
struct A {
x: i32
}
}
_ => {
struct A {
x: f64
}
}
}
}
}
cond!("i32");
cond!("f64");
fn main() {}
当前的 Rust 宏状态是否可行?
你要求的是不可能的。值得庆幸的是,您的要求和您的示例 表明您想要的 是两件不同的事情:
macro_rules! cond {
("i32") => {
struct A {
x: i32,
}
};
($el:expr) => {
struct B {
x: f64
}
};
}
cond!("i32");
cond!("f64");
fn main() {}
然而,从字面上理解你的问题:不,没有办法对宏中的条件进行任何类型的复杂测试,宏也不能设置或测试传递给它们的内容之外的任何类型的状态。您可以对宏的直接输入进行字面匹配,或者您可以将某些输入解析为有限数量的语法结构之一(然后您无法与之匹配),仅此而已。