我是个新手.我试图将一个有向图的邻接列表表示为char{vertex name}到(char,int){vertex name,cost}向量的HashMap.我希望最终的HashMap是不可变的,但我希望构建向量,然后不需要复制它来使其不可变.

My code is below. At the indicated line I get "cannot borrow immutable dereference (dereference is implicit, due to indexing) as mutable". This makes sense, as the Vec<(char,int)> in the map is not mutable. But I'm not sure how to fix it.

有没有办法在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 })
    }
}

推荐答案

[]带到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 })
    }
}

Rust相关问答推荐

在Tauri中获取ICoreWebView 2_7以打印PDF

包含嵌套 struct 的CSV

创建包含缺失值的框架

返回的future 不是`发送`

通过使用光标拖动角来绕其中心旋转矩形

变量需要parse()中的显式类型

考虑到Rust不允许多个可变引用,类似PyTorch的自动区分如何在Rust中工作?

在 Rust 中,为什么 10 个字符的字符串的 size_of_val() 返回 24 个字节?

需要哪些编译器优化来优化此递归调用?

实现AsyncWrite到hyper Sender时发生生命周期错误

如何从 rust 中的同一父目录导入文件

如何在 Rust 的 Hyper 异步闭包中从外部范围正确读取字符串值

将原始可变指针传递给 C FFI 后出现意外值

将 `&T` 转换为新类型 `&N`

使用 HashMap 条目时如何避免字符串键的短暂克隆?

如何在 Rust 中编写修改 struct 的函数

为什么 no_std crate 可以依赖于使用 std 的 crate?

如果我不想运行析构函数,如何移出具有析构函数的 struct ?

在使用大型表达式时(8k 行需要一小时编译),是否可以避免 Rust 中的二次编译时间?

如何在没有 `make_contiguous()` 的情况下对 VecDeque 进行排序或反转?