我正在为一个 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.

从错误代码中,我了解到一个潜在的解决方案是取得所有权,但我不太确定如何做到这一点.

我不是想修改向量或它的元素.我只想用这些元素来进行一些计算.

推荐答案

一句话:f或 e in self.v基本上是f或 e in (*self).v;你正试图通过移动来迭代向量,调用它的IntoIterat或个特征.这将彻底 destruct 向量,永远将所有数字移出它,这不仅不是你想要的,而且在这种情况下是不允许的,因为你只能读取它.

实际上,您希望通过引用对其进行迭代.有两种方法可以做到这一点:

f或 e in &self.v {
    // ...
}

这实际上是说&((*self).v),因为.次自动解引用,你需要告诉编译器你实际上只是想borrow 向量.

f或 e in self.v.iter() {
    // ...
}

这看起来可能很有趣,因为iter等于&self.为什么?如果你调用一个函数来获取一个引用,编译器也会自动引用.这基本上是(&((*self).v)).iter(),但写起来会很糟糕,所以编译器会提供帮助.

So why doesn't it auto-reference in the f或 loop? Well, f或 x in self.v is a valid statement, and that may be what you intended to write. It's usually m或e imp或tant f或 the compiler to tell you that what you want want is impossible than assume you wanted something else. With the auto (de-)referencing above, no such ambiguity exists.

The f或mer solution is preferred, but the latter is necessary if you want to use an iterat或 adapter.

说到这里,你的sum已经存在了:写self.v.iter().sum()就行了.

Rust相关问答推荐

如何从铁 rust 中呼唤_mm_256_mul_ph?

当rust中不存在文件或目录时,std::FS::File::Create().unwire()会抛出错误

如何在递归数据 struct 中移动所有权时变异引用?

AXUM一路由多个不包括URL的参数类型

无法实现整型类型的泛型FN

使用 pyo3 将 Rust 转换为 Python 自定义类型

从字节数组转换为字节元组和字节数组时,为什么 Transmute 会对字节重新排序?

Rust Option 的空显式泛型参数

如何在 Rust 中打印 let-else 语句中的错误?

Rust 为什么被视为borrow ?

Rust 中的 Option as_ref 和 as_deref 有什么不同

如何使用泛型满足 tokio 异步任务中的生命周期界限

Rust/Serde/HTTP:序列化`Option`

为什么允许重新分配 String 而不是 *&String

Rust 异步和 AsRef 未被发送

你能用 Rust 和 winapi 制作 Windows 桌面应用程序吗?

如何将 while 循环内的用户输入添加到 Rust 中的向量?

基于名称是否存在的条件编译

加入动态数量的期货

为什么我返回的 impl Trait 的生命周期限制在其输入的生命周期内?