如何在Rust中构建一个向量的哈希表?

15

我是一个Rust新手。 我正在尝试将有向图的邻接表表示为从char {顶点名称}到Vector of (char,int){顶点名称,成本}的HashMap。 我希望最终的HashMap是不可变的,但我想建立向量,然后不需要复制它就可以使其不可变。

我的代码如下。 在指定的行中,我得到“cannot borrow immutable dereference(由于索引而隐式解引用)作为可变”。这有道理,因为映射中的Vec<(char,int)>是不可变的。 但我不确定如何解决它。

Rust中有什么方法可以做到这一点吗?

pub struct Edge {
    to:     char,
    from:   char,
    weight: int
}

pub struct digraph {
    _vertices:  Vec<char>,
    _adj_list:  HashMap<char, Vec<(char,int)> >
}

impl digraph {
    pub fn new(nodes: &Vec<char>, edges: &Vec<Edge> ) -> Option<digraph> {
        let mut tmp_adj_list = HashMap::new();
        for node in (*nodes).iter() {
            tmp_adj_list.insert(*node, Vec::new());
        }
        for edge in (*edges).iter() {
            let Edge{ to: to, from:from, weight:weight } = *edge;
            if  !(*nodes).contains(&to) |  !(*nodes).contains(&from) {
                return None;
            }
            tmp_adj_list[from].push((to,weight))  // *********** error here
        }
        Some(digraph { _vertices: (*nodes).clone(), _adj_list: tmp_adj_list })
    }
}
1个回答

18

在 HashMap 中使用 [] 是对已废弃的 get(..) 函数的一种简写,其声明为:

fn get<'a>(&'a self, k: &K) -> &'a V

并且返回一个常量 (&) 引用。但是 Vec 的 push(..) 方法期望一个 &mut 引用,因此会出现错误。

你需要使用 HashMap 的 get_mut(..) 方法,它返回对值的 &mut 引用。

另外,有几点需要注意:

  • 调用方法时,自动解引用: (*foo).bar()foo.bar() 完全相同
  • 您可以在循环中使用 for &edge in edges.iter() {...} 自动解引用

将所有这些内容包含在内,您的函数将变为:

impl digraph {
    pub fn new(nodes: &Vec<char>, edges: &Vec<Edge> ) -> Option<digraph> {
        let mut tmp_adj_list = HashMap::new();
        for &node in nodes.iter() {
            tmp_adj_list.insert(node, Vec::new());
        }
        for &edge in edges.iter() {
            let Edge{ to: to, from:from, weight:weight } = edge;
            if  !nodes.contains(&to) |  !nodes.contains(&from) {
                return None;
            }
            tmp_adj_list.get_mut(&from).push((to,weight))
        }
        Some(digraph { _vertices: nodes.clone(), _adj_list: tmp_adj_list })
    }
}

1
有没有一种以高阶函数的方式来实现它的方法? - Charlie 木匠

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接