Search code examples
rustrust-macros

Check if macro param is defined in optional capture (Declarative Macro Syntax)


I am creating a fairly complex macro and can't use the overloading syntax to create my macros. I am trying to conditionally check if a prop has been defined within an optional capture group or not:

macro_rules! foo {
    (name: $name: ident$(, media: $media: tt)?) => {
        pub struct $name;
        impl $name {
            // how do i use media here and also provide default
            // const MEDIA: &str = IF_DEFINED $media { $media } ELSE { "DEFAULT" };
        }
    };
}

foo! {
    name: Hey,
    media: "hey"
}

foo! {
    name: Hey2
}

Playground Link


Solution

  • Within the constraints you mentioned, you can achieve conditional checking by the following workaround:

    macro_rules! foo {
        (name: $name: ident$(, media: $media: tt)?) => {
            
                pub struct $name;
         
                impl $name {
                    const MEDIA: &'static str = [$($media ,)? "DEFAULT"][0];
                }
        };
    }
    
    foo! {
        name: Hey,
        media: "hey"
    }
    
    foo! {
        name: Hey2
    }
    
    fn main() {
        println!("{}", Hey::MEDIA);
        println!("{}", Hey2::MEDIA);
    }
    

    Playground Link