检查可选捕获中是否定义了宏参数(声明性宏语法)

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

我正在创建一个相当复杂的宏,无法使用重载语法来创建我的宏。我正在尝试有条件地检查是否已在可选捕获组中定义道具:

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

在您提到的约束范围内,您可以通过以下解决方法实现条件检查:

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