我有包含变量的枚举:
enum Asymmetric {
One(i32),
Two(i32, i32),
}我只想改变一个已经存在的枚举的一个字段,而不重新分配整个枚举。我的代码(游乐场):
// Does not compile
fn main() {
let two = Asymmetric::Two(4, 5);
let mut vec = vec![two];
foo(&mut vec[0]);
}
fn foo(baa: &mut Asymmetric) {
match baa {
&mut Asymmetric::Two(x0, x1) => {
x0 = 6;
}
_ => {}
}
}这将导致此错误:
error[E0384]: re-assignment of immutable variable `x0`
--> src/main.rs:16:13
|
15 | &mut Asymmetric::Two(x0, x1) => {
| -- first assignment to `x0`
16 | x0 = 6;
| ^^^^^^ re-assignment of immutable variable发布于 2016-10-07 13:39:03
由于"match人机工程学“(在Rust 1.26,建议在此中引入),您可以编写如下代码:
fn foo(baa: &mut Asymmetric) {
match baa {
Asymmetric::Two(x0, _) => {
*x0 = 6;
}
_ => {}
}
}因为baa是一个可变引用,但是您要匹配的模式(Asymmetric::Two(x0, _))不是,所以名称x0自动绑定为可变引用。
您还可以使用ref mut手动完成此操作。请参阅此工作代码(游乐场):
fn foo(baa: &mut Asymmetric) {
match *baa {
Asymmetric::Two(ref mut x0, _) => {
*x0 = 6;
}
_ => {}
}
}一些与错误无关但提高代码质量的小更改:
*)执行matched-on值,而不是将&或&mut添加到匹配的每个模式中。_作为名称占位符。在您的例子中,您可以使用if let进一步简化代码。每当您只对一个match-case感兴趣时,就应该使用if let:
fn foo(baa: &mut Asymmetric) {
if let Asymmetric::Two(x0, _) = baa {
*x0 = 6;
}
}https://stackoverflow.com/questions/39918574
复制相似问题