以下代码无法编译:
#[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)
,这并不意味着在模式匹配中应该使用与号吗?
答案 0 :(得分:2)
我认为std :: Vec :: get成功会返回Some(&T)
是的,您可以选择参考。换句话说,x
中的Some(x)
是对Foo
实例的引用。
但是您想要:一个引用:打印元素而不将其从向量中删除的唯一方法是将引用传递给println
,而不是元素本身。这就是为什么
Some(x) => println!("ref {:?}", x),
是正确的方法。
这样做的时候
Some(&x) => println!("ref {:?}", x),
另一方面,由于&x
是对Foo实例的引用,x
是Foo
实例,因此,在匹配时将其从向量中移出,您无法使用get
获得的共享引用(而且您当然也不想这样做)。