Is there a way to use logic in a macro?

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 oversimplified.

2 Likes

wow its brilliant I didnt even think of this :slight_smile: 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

thats exactly what i did :slight_smile:

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.