我是一个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 })
}
}