【发布时间】: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;
}
}
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