【问题标题】:Best way to modify hashmap from reference to the value从参考值修改哈希图的最佳方法
【发布时间】:2017-05-22 18:59:23
【问题描述】:
use std::collections::{HashMap, HashSet};
use std::hash::{Hash};

fn test(data: &mut HashMap<String, HashSet<String>>) {
    match data.get("foo") {
        None => return,
        Some(xs) => {
            let xs: Vec<String> = xs.iter().map(|x| x.to_owned()).collect();
            // How to drop `data` here so that I can borrow `data`.
            for x in xs {
                // Mutable borrow occurs, because previous `data` is still in scope.
                data.remove(&x);
            }
        }
    }
}

上面的代码不起作用,因为我再次可变借用了data,而之前的借用仍在范围内。但是,我找不到一个简单的方法来解除之前借用的绑定。

另外,有没有更好的方法来复制xs,以便我可以在迭代时修改哈希图。

【问题讨论】:

标签: rust


【解决方案1】:

您非常接近解决方案。一旦你有了一个独立的向量,你就可以将它移出借用地图的范围:

use std::collections::{HashMap, HashSet};

fn test(data: &mut HashMap<String, HashSet<String>>) {
    let xs: Vec<String> = match data.get("foo") {
        None => return,
        Some(xs) => {
            xs.iter().map(|x| x.to_owned()).collect()
        }
    };
    for x in xs {
        data.remove(&x);
    }

}

Playground

【讨论】:

    猜你喜欢
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-09
    • 2010-10-04
    • 2010-09-21
    • 2021-05-09
    • 2014-04-21
    相关资源
    最近更新 更多