gpt4 book ai didi

rust - 如何匹配Some(&T)?

转载 作者:行者123 更新时间:2023-11-29 08:25:55 25 4
gpt4 key购买 nike

<分区>

以下代码无法编译:

#[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 => {}
}
}

抛出这个错误:

error[E0507]: cannot move out of a shared reference
--> src/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

我以为std::Vec<T>::get返回 Some(&T)在成功。这是否意味着应该在模式匹配中使用 & 符号?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com