简体   繁体   English

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

[英]Mutate a value stored in an enum in a Vec

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. last_mut()返回一个可变引用,我将i32作为可变引用。 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?为什么这不起作用?

You just need to match exactly what the error message says.您只需要完全匹配错误消息所说的内容。 It expects a &mut Test , so you should match on that:它需要一个&mut Test ,所以你应该匹配:

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:Rust 1.26 开始,您的原始代码按原样运行,不再需要显式refref mut关键字:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM