我正在为一个 struct 编写一个函数,其中包含一个Vec
,我试图遍历Vec
:
struct Object {
pub v: Vec<f32>,
}
impl Object {
pub fn sum(&self) -> f32 {
let mut sum = 0.0;
for e in self.v {
sum += e;
}
sum
}
}
然而,我得到了以下错误:
error[E0507]: cannot move out of borrowed content
--> src/lib.rs:8:18
|
8 | for e in self.v {
| ^^^^ cannot move out of borrowed content
我的理解是,因为self
是borrow 的,for循环迭代试图将v
的元素移出e
.
从错误代码中,我了解到一个潜在的解决方案是取得所有权,但我不太确定如何做到这一点.
我不是想修改向量或它的元素.我只想用这些元素来进行一些计算.