gpt4 book ai didi

rust - 匹配Option时 `Some(&a) => a`和 `Some(a) => *a`有什么区别?

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

为什么会通过:

fn f(v: Vec<isize>) -> (Vec<isize>, isize) {
match v.get(0) {
Some(&a) => (v, a),
_ => (v, 0)
}
}

Playground

但这不是吗?

fn f(v: Vec<isize>) -> (Vec<isize>, isize) {
match v.get(0) {
Some(a) => (v, *a),
_ => (v, 0)
}
}

Playground

error[E0505]: cannot move out of `v` because it is borrowed
--> src/main.rs:7:21
|
6 | match v.get(0) {
| - borrow of `v` occurs here
7 | Some(a) => (v, *a),
| ^ move out of `v` occurs here

最佳答案

v.get(0)返回对向量中元素的引用,因此您正在匹配 &isizeVec 现在在 match arm 中借用了。

在第一个代码片段中,您复制了 isize,所以这里没有借用 Vec。在第二个片段中,Vec 仍然是借用的,所以您不能将它移出范围。

但是,您应该考虑使用if letunwrap_or:

fn f(v: Vec<isize>) -> (Vec<isize>, isize) {
let a = v.get(0).cloned();
(v, a.unwrap_or(0))
}

Playground

fn f(v: Vec<isize>) -> (Vec<isize>, isize) {
if let Some(&a) = v.get(0) {
(v, a)
} else {
(v, 0)
}
}

Playground


另见:

关于rust - 匹配Option时 `Some(&a) => a`和 `Some(a) => *a`有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51044568/

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