向量具有结构的多次迭代“无法移出借用的内容”

时间:2019-04-02 07:09:11

标签: rust borrow-checker borrowing

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

我在做什么错?

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

2 个答案:

答案 0 :(得分: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()
}

还可以查看以下问题以进一步澄清:

答案 1 :(得分: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;
    }
}