这个问题在这里已有答案:
我需要在循环中的每次迭代中迭代带有结构的向量。只要向量不包含结构,它就可以正常工作。我尝试过很多不同的解决方案,但总会遇到某种所有权问题。
我究竟做错了什么?
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;
}
}
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
问题是,你的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()
}
另请查看这些问题以获得进一步说明:
这是问题的解决方案,它需要借用自我对象和生命周期规范。
从&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;
}
}