以下代码将无法编译:
#[derive(Debug)]
struct Foo {
x: i32,
}
pub fn main() {
let a = vec![Foo{x:1}, Foo{x:2}];
match a.get(0) {
Some(&x) => println!("ref {:?}", x),
None => {},
}
}
rustc抱怨:
$ rustc main.rs
error[E0507]: cannot move out of a shared reference
--> main.rs:8:11
|
8 | match a.get(0) {
| ^^^^^^^^
9 | Some(&x) => println!("ref {:?}", x),
| -
| |
| data moved here
| move occurs because `x` has type `Foo`, which does not implement the `Copy` trait
error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
我以为std::Vec<T>::get
成功返回Some(&T)
,这并不意味着在模式匹配中应使用与号吗?
我以为std :: Vec :::成功获得回报Some(&T)
是的,您可以选择参考。否则,x
中的Some(x)
是对Foo
实例的引用。
但是您do want引用:打印元素而不将其从向量中删除的唯一方法是将引用传递给println
,而不是元素本身。这就是为什么
Some(x) => println!("ref {:?}", x),
是正确的方法。
执行时
Some(&x) => println!("ref {:?}", x),
另一方面,由于&x
是Foo实例的引用,x
是Foo
实例,因此在匹配时将其从向量中移出,您将无法执行与get
共享的参考(以及某些您肯定不想做的事情)。