如何匹配Some(&T)?

问题描述 投票:0回答:1

以下代码将无法编译:

#[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),这并不意味着在模式匹配中应使用与号吗?

rust
1个回答
0
投票

我以为std :: Vec :::成功获得回报Some(&T)

是的,您可以选择参考。否则,x中的Some(x)是对Foo实例的引用。

但是您do want引用:打印元素而不将其从向量中删除的唯一方法是将引用传递给println,而不是元素本身。这就是为什么

Some(x) => println!("ref {:?}", x),

是正确的方法。

执行时

Some(&x) => println!("ref {:?}", x),

另一方面,由于&x是Foo实例的引用,xFoo实例,因此在匹配时将其从向量中移出,您将无法执行与get共享的参考(以及某些您肯定不想做的事情)。

© www.soinside.com 2019 - 2024. All rights reserved.