I want to set the compile-time condition in macros when it generates code outside the functions. I need something like that:
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() {}
Or maybe something like that:
macro_rules! cond {
( $cond_el:expr ) => {
match $cond_el {
"i32" => {
struct A {
x: i32
}
}
_ => {
struct A {
x: f64
}
}
}
}
}
cond!("i32");
cond!("f64");
fn main() {}
Is it possible with current Rust macros state?
You can define any macro on the compiler command line with -D. Use that to specify the model or variant you want, and based on that, #ifdefs in the code enable the other relevant macros.
Compile-time is the time at which the source code is converted into an executable code while the run time is the time at which the executable code is started running. Both the compile-time and runtime refer to different types of error.
What you're asking for is impossible. Thankfully, what you're asking for and what your examples suggest you want are two different things:
macro_rules! cond {
("i32") => {
struct A {
x: i32,
}
};
($el:expr) => {
struct B {
x: f64
}
};
}
cond!("i32");
cond!("f64");
fn main() {}
Taking your question literally, however: no, there is no way to do any sort of complex testing of conditions in macros, nor can macros set or test any kind of state outside of what's passed in to them. You can do literal matches of the direct input to the macro, or you can parse some input as one of a limited number of syntax constructs (which you then cannot match against), and that's about it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With