作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
为什么会通过:
fn f(v: Vec<isize>) -> (Vec<isize>, isize) {
match v.get(0) {
Some(&a) => (v, a),
_ => (v, 0)
}
}
但这不是吗?
fn f(v: Vec<isize>) -> (Vec<isize>, isize) {
match v.get(0) {
Some(a) => (v, *a),
_ => (v, 0)
}
}
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)
返回对向量中元素的引用,因此您正在匹配 &isize
。 Vec
现在在 match arm 中借用了。
在第一个代码片段中,您复制了 isize
,所以这里没有借用 Vec
。在第二个片段中,Vec
仍然是借用的,所以您不能将它移出范围。
但是,您应该考虑使用if let
或unwrap_or
:
fn f(v: Vec<isize>) -> (Vec<isize>, isize) {
let a = v.get(0).cloned();
(v, a.unwrap_or(0))
}
fn f(v: Vec<isize>) -> (Vec<isize>, isize) {
if let Some(&a) = v.get(0) {
(v, a)
} else {
(v, 0)
}
}
另见:
关于rust - 匹配Option时 `Some(&a) => a`和 `Some(a) => *a`有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51044568/
我是一名优秀的程序员,十分优秀!