我需要在循环的每次迭代中使用结构迭代向量。只要向量不包含结构,它就可以正常工作。我尝试了许多不同的解决方案,但始终会遇到某种所有权问题。
我在做什么错?
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
答案 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;
}
}