I'm learning Rust and implementing a project I know pretty well: parsing text. Given some line of text, I want to identify if it's a Foo
or a Bar
:
Foooooooooooo
Baaar
(This is not the real project, but it's a close approximation.)
I've got some Rust basics, so I thought I'd like to get a bit fancy. I want to create a Vec
of objects that represent each line of data. The closest approximation I got was:
pub struct FooType {
pub length:i32
}
pub struct BarType {
pub length:i32
}
pub enum FooBar {
Foo(FooType),
Bar(BarType)
}
let mut vec: Vec<FooBar> = Vec::new();
vec.push(FooType { length: 23 });
vec.push(BarType { length: 43 });
let v = vec.pop().unwrap();
assert_eq!(v.length, 23);
(This is roughly real code.)
I thought: ok, I'll have a vector of an enum, and that enum will contain struct
s, and those struct
s will have the properties I care about given each line.
However, the code doesn't compile:
Problem One
vec.push(FooType { id: 23 });
^^^^^^^^^^^^^^^^^^ expected enum `tests::it_works::FooBar`, found struct `tests::it_works::FooType`
I called it a vector of FooBar
, and I'm trying to pass a FooType
. I think I understand the error, but how else should I create a vector so that it can be filled with one of these two types? Switching this to FooBar::FooType
yields ambiguous associated type
, which I do not understand.
Problem Two
error: no field `length` on type `tests::it_works::FooBar`
--> src/lib.rs:19:18
|
19 | assert_eq!(v.length, 23);
|
Ok, so, because it thinks that the type must be that enum FooBar
, there's no id
field on the enum
. How would I fix that? Would that need an impl FooBar
that defines an length()
method, using match
to determine what to perform (call the field length
)?
Thanks for any help!