2015-12-07 51 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 
    } 
}