无法移出封闭内的借来的内容[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

这里生锈新手。我正在尝试编写一个消耗传递的向量的函数,修改它,将它附加到另一个向量并返回它。

这是我的代码:

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。我做错了什么?什么被传递到关闭?

rust borrow-checker
1个回答
1
投票

t.0试图将Stringt所指的元组中移出,但是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
}

重新使用Strings可能更有效,而不是用String::from创建新的。

© www.soinside.com 2019 - 2024. All rights reserved.