I've been trying to find this in the documentation, but without success. Is there any way to enable field access to an enum? Specifically, I'd love to be able to access fields with field expressions when the same named field (with the same type) is available across all variants of an enum. Is this possible? It would certainly be convenient.
This isn't possible, at least at the moment. I guess it might be possible to implement, with laying out the common fields in the enum so that their offset doesn't depend on the variant.
A common solution is to add a higher-level Struct that contains the Enum (minus common fields) and the common fields. This is what Rust itself does with its AST nodes, for example. The disadvantage is that it gets more cumbersome to pattern-match on nested structures.
I think what he is after is not having to do a pattern match or have an accessor containing a pattern match if the field is available and identical in all variants.
Now, a syntax extension could possibly expand an enum to include an implementation of accessor methods. You can probably also solve the simple cases of this with just a macro.
Having it be a field access would be more complicated. It would certainly be a language change, and you'd need guaranteed layout of the variant fields.
Thanks for the rapid response. Indeed I was thinking in terms of designing a nice API. It would be lovely to not require users to pattern match, but to only require them to read about one type. Sounds like my solution should be to either create an accessor method, or to used a struct holding an enum, which seems clumsy to me. Or to just make people pattern match.