I have a macro that has a optional variable $(name=$name:expr)?
Is there a way to do one thing if name part is used and another if not?
fn setName(){
//just a oversimplified example of to what I am trying to do
$(
println!("set {}",$name)
)?
//$else(println!("unset"))
}
Your example is a bit minimized for me to be sure this is what you're looking for, but here's an example of different output based on the presence or absence of name=AnExpression
in the macro call.
2 Likes
You might be able to do it with another "helper" macro. E.g.
#[macro_export]
macro_rules! my_macro {
($(name=$name:expr)?) => {
fn set_name(){
$crate::set_name_helper!{$($name)?}
}
}
}
#[macro_export]
#[doc(hidden)]
macro_rules! set_name_helper {
() => {
println!("unset")
};
($name:expr) => {
println!("set {}", $name)
};
}
fn foo() {
my_macro!(name=42);
set_name();
}
fn bar() {
my_macro!();
set_name();
}
fn main() {
foo();
bar();
}
(playground )
set 42
unset
It's impossible to tell how good this will work for you as your example is indeed a bit over simplified .
2 Likes
wow its brilliant I didnt even think of this thanks
You could even write a general helper macro, e.g. like this
#[macro_export]
macro_rules! my_macro {
($(name=$name:expr)?) => {
fn set_name(){
$crate::conditional!($([println!("set {}", $name)])? else println!("unset"))
}
}
}
#[macro_export]
#[doc(hidden)]
macro_rules! conditional {
(else $e:expr) => {
$e
};
([$e:expr] else $_e:expr) => {
$e
};
}
fn foo() {
my_macro!(name = 42);
set_name();
}
fn bar() {
my_macro!();
set_name();
}
fn main() {
foo();
bar();
}
2 Likes
system
Closed
February 27, 2022, 10:39pm
7
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.