1

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

sno2
  • 3,274
  • 11
  • 37
  • 1
    *"can't use the overloading syntax"* - why not? It seems like a natural choice to me – kmdreko Oct 07 '21 at 01:03
  • @kmdreko because my param syntax is using the optional thing in a repeat group so I can't overload it – sno2 Oct 07 '21 at 01:10
  • Why do you make `$media` in macro repeated? Referring to `const MEDIA: &str` I consider only one is needed. – rustyhu Oct 07 '21 at 04:32
  • @rustyhu because my macro is more complex than the example and uses a lot of other code in my crate so I listed the constraints out and then gave a minimal reproduction – sno2 Oct 07 '21 at 04:34
  • @sno2 Could you post a more realistic example that shows why you assume you can't use the overloading syntax? Maybe there's a catch allowing that you actually could use it. – phimuemue Oct 07 '21 at 08:48
  • You can always use recursion and use overload syntax in the inner recursion levels: [playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d82161a7ab896c09ca1cbc50ac8ecaae) – Jmb Oct 07 '21 at 09:25

1 Answers1

1

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

sno2
  • 3,274
  • 11
  • 37
Mihir Luthra
  • 6,059
  • 3
  • 14
  • 39