Mutate a value stored in an enum in a Vec

泄露秘密 提交于 2020-03-04 19:37:46

问题


The following code fails to compile with the error below:

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() returns a mutable reference, and I'm taking the i32 as a mutable reference. I've tried making the mutability even more clear as follows, but I get the same compiler error.

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

Why doesn't this work?


回答1:


You just need to match exactly what the error message says. It expects a &mut Test, so you should match on that:

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

Here it is running in the playground.

As of Rust 1.26, your original code works as-is and the explicit ref and ref mut keywords are no longer required:

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


来源:https://stackoverflow.com/questions/47170186/mutate-a-value-stored-in-an-enum-in-a-vec

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!