无法在闭包内移出借用的内容
Cannot move out borrowed content inside closure
这里是 Rust 新手。我正在尝试编写一个函数,该函数使用传递的向量,对其进行修改,将其附加到另一个向量并 returns 它。
这是我的代码:
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
}
但是,我在 t.0
得到了一个 cannot move out borrowed content
。我做错了什么?什么被传递到闭包中?
t.0
尝试 将 String
移出 t
引用的元组,但 t
仅借用它。那是因为 .iter()
为您提供了一个迭代器,该迭代器为您提供了对值的引用。如果您使用 into_iter()
而不是 iter()
,您将 消耗 other
的所有值,而不仅仅是 借用 他们,因为 other.into_iter()
消耗 other
.
在您的具体示例中,完全重复使用 other
而不是使用(部分)取自 other
的内容创建新的 Vec
会更有效,并且然后删除 other
:
fn try2(mut other: Vec<(String, String)>) -> Vec<(String, String)> {
for x in &mut other {
x.1 = String::from("abc");
}
other
}
重复使用 String
比用 String::from
创建新的更有效。
这里是 Rust 新手。我正在尝试编写一个函数,该函数使用传递的向量,对其进行修改,将其附加到另一个向量并 returns 它。
这是我的代码:
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
}
但是,我在 t.0
得到了一个 cannot move out borrowed content
。我做错了什么?什么被传递到闭包中?
t.0
尝试 将 String
移出 t
引用的元组,但 t
仅借用它。那是因为 .iter()
为您提供了一个迭代器,该迭代器为您提供了对值的引用。如果您使用 into_iter()
而不是 iter()
,您将 消耗 other
的所有值,而不仅仅是 借用 他们,因为 other.into_iter()
消耗 other
.
在您的具体示例中,完全重复使用 other
而不是使用(部分)取自 other
的内容创建新的 Vec
会更有效,并且然后删除 other
:
fn try2(mut other: Vec<(String, String)>) -> Vec<(String, String)> {
for x in &mut other {
x.1 = String::from("abc");
}
other
}
重复使用 String
比用 String::from
创建新的更有效。