syn icon indicating copy to clipboard operation
syn copied to clipboard

Consider adding `as_xx() -> Option<...>` functions to enums

Open tgross35 opened this issue 2 years ago • 0 comments

serde_json::Value has an easy way to map an enum variant to an option, e.g.

let val = Value::("abc")

assert_eq!(val.as_str(), Some("abc"));
assert_eq!(val.as_bool(), None);

I feel like this pattern would work well for syn's enums, to help simplify token parsing.

As an example, I am attempting to find the a Type within a impl that this proc macro is applied to. The current implementation is not terrible using a rules macro:

macro_rules! match_variant {
    ($variant:path) => {
        |x| {
            if let $variant(value) = x { Some(value) } else { None }
        }
    }
}
// ...
let tmp: &ImplItemType = impl_items
    .iter()
    .find_map(match_variant!(ImplItem::Type))
    .unwrap();

But the suggested change would eliminate its need:

let tmp: &ImplItemType = impl_items
    .iter()
    .find_map(|x| x.as_type())
    .unwrap();

If a change like this is out of scope, perhaps it would be good to include the above macro (suggested by kpreid on discord) in syn. Or, there may be an existing option that simplifies pattern matching that I am happy to learn about.

tgross35 avatar Sep 29 '22 05:09 tgross35