改变存储在Vec中的枚举中的值

时间:2017-11-08 01:37:15

标签: rust

以下代码无法使用以下错误进行编译:

enum Test {
    C(i32),
}

fn main() {
    let mut v = Vec::new();

    v.push(Test::C(0));

    if let Some(Test::C(ref mut c)) = v.last_mut() {
        *c = *c + 1;
    }
}
  
error[E0308]: mismatched types
  --> src/main.rs:10:17
   |
10 |     if let Some(Test::C(ref mut c)) = v.last_mut() {
   |                 ^^^^^^^^^^^^^^^^^^ expected &mut Test, found enum `Test`
   |
   = note: expected type `&mut Test`
              found type `Test`

last_mut()返回一个可变引用,我将i32作为可变引用。我已经尝试使可变性更加清晰,如下所示,但我得到了相同的编译器错误。

if let Some(ref mut e) = v.last_mut() {
    if let Test::C(ref mut c) = e {
        *c = *c + 1;
    }
}

为什么这不起作用?

1 个答案:

答案 0 :(得分:3)

您只需要准确匹配错误消息所说的内容。它需要一个&mut Test,所以你应该匹配:

if let Some(&mut Test::C(ref mut c)) = v.last_mut() {
    //     ^^^^^^
    *c = *c + 1;
}

此处it is running in the playground