我想获取数组中最大的项,其中最大项是在自定义逻辑中定义的。
这里是编译的i32
版本
fn largest(list: &[i32]) -> i32 {
let mut largest = list[0];
for &item in list.iter() {
if item > largest {
largest = item;
}
}
largest
}
这里是一个不编译的struct版本
#[derive(Debug, Clone)]
struct Point {
x: f32,
y: f32,
}
fn largestPoint(list: &[Point]) -> Point {
// Defaulting to something
let mut myPoint: Point = Point { x: 1.0, y: 1.0 };
for &item in list.iter() {
if (item.x > myPoint.x) {
myPoint = item.clone();
}
}
myPoint
}
这个编译错误是什么意思?
error[E0507]: cannot move out of borrowed content
--> src/main.rs:11:9
|
11 | for &item in list.iter() {
| ^----
| ||
| |hint: to prevent move, use `ref item` or `ref mut item`
| cannot move out of borrowed content
难道 .iter()
不总是对原始列表的引用吗?如何通过引用移动项目?
最佳答案
for &item in list.iter() {
if (item.x > myPoint.x) {
myPoint = item.clone();
}
}
上面的代码不起作用,因为 for
循环遍历一组对 &Point
类型数组中项目的引用。当您将其绑定(bind)到 &item
时,您正在尝试解构引用。这与 i32
列表一起工作,因为 i32
实现了 Copy
并且因此可以仅复制该项目但使用 Point< 列表
s 它必须移动所有权,这是不可能的。
您可以通过将 &item
更改为 item
来修复您的代码。
for item in list.iter() {
if (item.x > myPoint.x) {
myPoint = item.clone();
}
}
如果仍然不清楚,请考虑这个例子。
for &(x, y) in [(1, 2), (2, 30)].iter() {
println!("({}, {})", x, y);
}
另请查看解构示例 at Rust by Example .
关于rust - 为什么我在使用 "cannot move out of borrowed content"时得到 `for &item in` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47084908/