2015-12-07 50 views
1

我有一個枚舉與多個單字段元組結構變體。每個元組結構字段都是不同的結構。我想這樣的代碼:枚舉結構變體的訪問字段用一個元組結構包裝

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 
    } 
} 

編譯器說:

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

我試着在this question找到了解決方案,但它說:

error: cannot borrow immutable anonymous field as mutable

如何修改內容領域矢量x

回答

3

這是因爲您的向量和參考element是不可變的。試試這個:

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 
    } 
}