this post was submitted on 16 Jun 2024
28 points (96.7% liked)
Rust
6030 readers
2 users here now
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Wormhole
Credits
- The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
I think the point is that the variable itself is an Option. Your example only works for literal Option (although the value inside the optional itself might not be a literal).
One option to OP's problem is to use an auxiliary trait implemented on both string and Option
This looks something like the following
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=aa68fe540dbd09821ecc482423227b46
~~* Two of your macro rules are not used 😉 (expand to see which ones).~~
Option<&str>
. If it did, we would lose literalNone
support 😉Similar impl, but using wrapper struct with
From
implsThe macro rules are all used. (Macros are matched from top to bottom by the declared match types. The ident/expressions can't match until after the more text based Option matching.)
I didn't make Option<&str> an option because the struct is for type
Option<String>
. It does support Option though.It looks like the following, and uses the last match case.
With macro expansion
There's not anything stopping it from supporting Option<&str> though. This would be the implementation
Oops. I was looking at it wrong.
Re-read the end of OP's requirements.
I made an edit.
There's not anything stopping it from supporting Option<&str> though. This would be the implementation
It's also possible to just make it generic over Option types
Yes, but then the concrete type of
None
literals becomes unknown, which is what I was trying to point out.I had commented something similar to stating it was possible to pass the inference problem to the struct if the goal was to support more types, but I removed it because I didn't think my example was easy to understand when reading it later. I made a better example though
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=8651fa6121840658b4b6249399f693c7