pengowen123
pengowen123

Reputation: 1017

Access fields of enum struct variant wrapped with a tuple struct

I have an enum with multiple single field tuple struct variants. Each tuple struct field is a different struct. I tried this code:

struct Foo { a: i32 }
struct Bar { b: i32 }

enum Foobar {
    Foo(Foo),
    Bar(Bar)
}

impl Foobar {
    fn new_foo() -> Foobar {
        Foobar::Foo(Foo { a: 1 })
    }
    fn new_bar() -> Foobar {
        Foobar::Bar(Bar { b: 2 })
    }
}

fn main() {
    let x = vec![Foobar::new_foo(), Foobar::new_bar()];
    let mut i = 0;

    while i < x.len() {
        let element = &x[i];
        match element {
            &Foobar::Foo(_) => { x[i].a = 3 },
            &Foobar::Bar(_) => { x[i].b = 4 }
        }
        i += 1
    }
}

The compiler says:

error: attempted access of field a on type Foobar, but no field with that name was found

I tried the solution found in this question but it says:

error: cannot borrow immutable anonymous field as mutable

How can I modify the fields of the content of vector x?

Upvotes: 2

Views: 1434

Answers (1)

antoyo
antoyo

Reputation: 11933

This is because your vector and the reference element are immutable. Try this:

fn main() {
    let mut x = vec![Foobar::new_foo(), Foobar::new_bar()];
    let mut i = 0;

    while i < x.len() {
        let element = &mut x[i];
        match *element {
            Foobar::Foo(Foo { ref mut a }) => { *a = 3 },
            Foobar::Bar(Bar { ref mut b }) => { *b = 4 }
        }
        i += 1
    }
}

Upvotes: 4

Related Questions