How to build hashmap vectors in rust?

I am new to Rust. I am trying to present a list of adjacent oriented graphs as a HashMap from char {vertex name} to Vector of (char, int) {vertex name, cost}. I want the final HashMap to be immutable, but I would like to create a vector, and then I don't need to make a copy of it to make it immutable.

My code is below. On the specified line, I get "cannot take immutable dereferencing (dereferencing implicitly, due to indexing) as mutable." This makes sense, since Vec <(char, int)> in the map does not change. But I'm not sure how to fix this.

Is there any way to do this in 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 })
    }
}
+4
source share
1 answer

[] HashMap ( ) get(..), :

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

(&). push(..) Vec &mut, .

, get_mut(..) HashMap, &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 })
    }
}
+8

All Articles