【发布时间】:2021-04-17 05:37:58
【问题描述】:
我可以更改 vec 的最后一个元素:
#[derive(Debug)]
enum Type {
A,
B,
C,
}
fn main() {
let mut v = vec![Type::A, Type::B, Type::B];
match v.last_mut(){
None => v.push(Type::A),
Some(last) => *last = Type::C,
}
println!("{:?}", v)
}
==> 打印出[A, B, C]。
但如果我的枚举常量有数据,我似乎无法捕获它们...... 例如:
#[derive(Debug)]
enum Type {
A(i32),
B(i32),
C(i32),
}
fn main() {
let mut v = vec![Type::A(0), Type::B(1), Type::B(2)];
match v.last_mut(){
None => v.push(Type::A(0)),
Some(last @ Type::B(_)) => *last = Type::C(42),
Some(Type::A(_)) | Some(Type::C(_)) => {}
}
println!("{:?}", v);
}
==> 打印 [A(0), B(1), C(42)]
上面的工作只是因为我在Type::B(_) 里面放了一个_。
如果我尝试使用此行捕获它以在Type::C() 中使用:
Some(last @ Type::B(p)) => *last = Type::C(*p),
我收到三个奇怪的错误:
error: borrow of moved value
--> src/main.rs:13:14
|
13 | Some(last @ Type::B(p)) => *last = Type::C(*p),
| ----^^^^^^^^^^^-^
| | |
| | value borrowed here after move
| value moved into `last` here
| move occurs because `last` has type `&mut Type` which does not implement the `Copy` trait
error[E0658]: pattern bindings after an `@` are unstable
--> src/main.rs:13:29
|
13 | Some(last @ Type::B(p)) => *last = Type::C(*p),
| ^
|
= note: see issue #65490 <https://github.com/rust-lang/rust/issues/65490> for more information
error[E0382]: borrow of moved value
--> src/main.rs:13:29
|
13 | Some(last @ Type::B(p)) => *last = Type::C(*p),
| ---------------^-
| | |
| | value borrowed here after move
| value moved here
|
= note: move occurs because value has type `&mut Type`, which does not implement the `Copy` trait
help: borrow this field in the pattern to avoid moving the value
|
13 | Some(ref last @ Type::B(p)) => *last = Type::C(*p),
| ^^^
error: aborting due to 3 previous errors
我怎样才能完成这项工作,即捕获 B 的当前值(a &mut i32),并将其传递给 C?
【问题讨论】:
标签: design-patterns rust match capture mutable