【问题标题】:Multiple iterations of vector with structs "cannot move out of borrowed content" [duplicate]具有结构的向量的多次迭代“无法移出借用的内容”[重复]
【发布时间】:2019-08-23 10:18:37
【问题描述】:

我需要在循环中的每次迭代中迭代一个带有结构的向量。只要向量不包含结构,它就可以正常工作。我尝试了许多不同的解决方案,但总是遇到某种所有权问题。

我做错了什么?

struct Element {
    title: String,
}

impl Element {
    pub fn get_title(self) -> String {
        self.title
    }
}

fn main() {
    let mut items: Vec<Element> = Vec::new();
    items.push(Element {
        title: "Random".to_string(),
    });
    items.push(Element {
        title: "Gregor".to_string(),
    });

    let mut i = 0;
    while i < 10 {
        for item in &items {
            println!("Loop {} item {}", i, item.get_title());
        }
        i = i + 1;
    }
}

playground

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:23:44
   |
23 |             println!("Loop {} item {}", i, item.get_title());
   |                                            ^^^^ cannot move out of borrowed content

【问题讨论】:

  • 我建议你阅读book
  • 谢谢 我已经读了这本书 3 遍了,我不明白你怎么能认为这是重复的问题。另一个问题在二维循环中访问相同的变量,我的问题没有
  • “另一个问题在二维循环中访问相同的变量,我的问题没有”这不会改变任何东西。重复的要点是,如果您进行迭代,因此您借用了该值,您将无法使用消耗该值的函数。
  • 请注意,您可以大幅simplify your example by manually unrolling the loop。一旦你让它尽可能简单,就会更清楚为什么它是重复的。您还需要在实际代码中使用vec!

标签: rust borrow-checker borrowing


【解决方案1】:

问题是,您的get_title 方法使用Element,因此只能调用一次。 您必须接受 &amp;self 作为参数,并且可以执行以下操作:

要么返回 &amp;str 而不是 String

pub fn get_title(&self) -> &str {
    &self.title
}

如果你真的想返回一个String 结构体,或者克隆String

pub fn get_title(&self) -> String {
    self.title.clone()
}

还可以查看这些问题以获得进一步的说明:

【讨论】:

【解决方案2】:

这是问题的解决方案,它需要借用自我对象生命周期规范

&amp;String 移动到&amp;str 只是为了遵循更好的做法,谢谢@hellow Playground 2

struct Element<'a> {
    title: &'a str
}

impl <'a>Element<'a> {
    pub fn get_title(&self) -> &'a str {
        &self.title
    }
}

fn main() {
    let mut items: Vec<Element> = Vec::new();
    items.push(Element { title: "Random" });
    items.push(Element { title: "Gregor" });

    let mut i = 0;
    while i < 10 {
        for item in &items {
            println!("Loop {} item {}", i, item.get_title());
        }
        i = i + 1;
    }
}

【讨论】:

  • 现在你让你的结构保持引用。为什么?你超过了目标。
  • 这只是一个假设的例子,如果有意义的话,我正在研究一个更高级的例子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-13
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 2019-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多