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:

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:/

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.