问题
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