这个问题在这里已有答案:
这里生锈新手。我正在尝试编写一个消耗传递的向量的函数,修改它,将它附加到另一个向量并返回它。
这是我的代码:
fn try(other: Vec<(String, String)>) -> Vec<(String, String)> {
let mut res = Vec::new();
let mut neg: Vec<(String,String)> = other
.iter()
.map(|t| (t.0, String::from("abc")))
.collect();
res.append(&mut neg);
res
}
但是,我在cannot move out borrowed content
得到了t.0
。我做错了什么?什么被传递到关闭?
t.0
试图将String
从t
所指的元组中移出,但是t
只能借用它。这是因为.iter()
为您提供了一个迭代器,可以为您提供值的引用。如果你使用into_iter()
而不是iter()
你可以消耗other
的所有值,而不是仅仅借用它们,因为other.into_iter()
消耗other
。
在你的具体例子中,完全重用other
而不是创建一个新的Vec
(内容(部分)取自other
,然后删除other
会更有效率:
fn try2(mut other: Vec<(String, String)>) -> Vec<(String, String)> {
for x in &mut other {
x.1 = String::from("abc");
}
other
}
重新使用String
s可能更有效,而不是用String::from
创建新的。