Reputation: 1585
How do I access field c
inside struct
of type B_
inside enum
of type A
in this case?
enum A {
B(B_),
D(D_)
}
enum D_ { D_1, D_2 }
struct B_ {
c: Vec<i32>,
}
Obvious stuff like this doesn't work:
let y = A::B;
y.c = Vec::new();
Upvotes: 2
Views: 1240
Reputation: 4709
I think the first problem is that what you really want is y
to be of type A
, so it cannot have a field named c
in the first place. y
can be A::B
or A::D
. Only if y
is an A::B
variant, then you can get the B_
object inside the variant and then get the c
.
The second problem in your code is that you are not initializing y
to be an A::B
variant. The expression A::B
is of type fn(B_) -> A {A::B}
which is a kind of constructor function (automagically generated by the compiler) for A
enums.
The following code initialize y
correctly and get c
:
enum A {
B(B_),
D(D_)
}
enum D_ { D_1, D_2 }
struct B_ {
c: Vec<i32>,
}
fn main() {
let y = A::B( B_ { c : Vec::new() });
// Check if y is an A::B, so we can get the B_ object inside
// by deconstruction. Then we can get c.
if let A::B(b_) = y {
println!("{:?}", b_.c);
}
}
Maybe you thought that A::B
is a kind of B
type defined "inside" A
, which is not how enums work is Rust.
Upvotes: 3