具有结构的向量的多次迭代“不能移出借来的内容”[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

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

我究竟做错了什么?

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
rust borrow-checker borrowing
2个回答
2
投票

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

要么返回&str而不是String

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

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

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

另请查看这些问题以获得进一步说明:


0
投票

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

&String搬到&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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.