I've reached a point where I've been trying to add common data to a particular enum among it's variants, and discovered a limitation that had not previously occurred to me. There's no way (without a macro I suppose) to get at the inner data of an enum value, unless the variant is known. Is that correct?
While the goal behind the following code is obvious, it will not compile:
(I understand positional references only work with tuples--- that's not my point, they could also "in theory at least" refer to elements in an enum that share a common type.)
#[derive(Debug)]
enum Foo {
Bar(u32),
Bink(u32),
}
use Foo::*;
fn main() {
let bar = Bar(10);
let bink = Bink(20);
println!("bar={:?}, bink={:?}", bar, bink);
println!("bink num = {}", bink.0);
}
The error message is:
error[E0609]: no field `0` on type `Foo`
--> src/main.rs:14:36
|
14 | println!("bink num = {}", bink.0);
|
What's interesting about the error message is that it would seem to imply there is a way to attach a field named 0
to an enum. But as far as I know this is not possible (is it?)
For example, why doesn't the message say "enums cannot have fields?" instead of "Foo doesn't have a field named xyz?
At any rate. It would be nice, if, when all the variants of an enum share an identical type, that there were a way to refer to that data by it's position instead of having to pull it would with some long match statement, etc...
Of course the architecture could be modified to have an outer 'struct" that holds the data shared among the variants, however that would seem to add unnecessary complexity.