Trying to use variants from types provided by caller in a macro

I'm trying to create a macro that uses variants from a type provided by the caller but it does not work.

How can I fix this? Example:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=34c24c48474945813d7c9ce0c20dbda3

Thanks in advance.

If the user can pass in arbitrary types here, how does your macro code know what variants the type has?

Once tokenized as a :path, a macro metavariable cannot be appended more path segments. So no ::Variant afterwards.

Either capture a raw stream of tokens: $(stuff:tt)* $($stuff:tt)* (expanded as $($stuff)* ), or, if the type is no longer generic (e.g., Option<_> rather than Option), you may get away capturing $stuff:ty and expanding it as <$stuff>::Variant, but it will be fragile.

The user cannot pass in arbitrary types here. The macro meant to contain stuff that I had to copy otherwise manually but it is not a general solution.

I've tried both ideas and they don't seem to work or I still misunderstand something:/

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a794ab70ee31ba51e38161d1c5ae6139

Could you please take a look at them?

You forgot a $ on your first macro, and the second macro requires <_> to be given to the Option, as it will be used within < ... > syntax which requires it.

  • Playground (fails with type inference but the macro has nothing to do with that).

Hmm, you wrote it originally without that extra $ in your example.
But it works now!:slight_smile: Thank you very much!

Wops :sweat_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.