首页 > 解决方案 > Rust: 不能使用 HashMap::

问题描述

我有一个名为 Point 的结构元组。它是一个二维笛卡尔坐标。我需要使用一个点作为哈希图中的键,但编译器拒绝。我该如何处理?

#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
struct Point(i16, i16);

const ROOT: Point = Point(0,0);

let mut visited = std::collections::HashMap::<Point,bool>::new();
visited[&ROOT] = true;

编译器错误如下:

error[E0594]: cannot assign to data in an index of `std::collections::HashMap<Point, bool>`
   --> src/main.rs:124:3
    |
124 |         visited[&ROOT] = true;
    |         ^^^^^^^^^^^^^^^^^^^^^ cannot assign
    |
    = help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `std::collections::HashMap<Point, bool>`

标签: indexingrusthashmap

解决方案


HashMap不执行IndexMut。条目的突变通过get_mut()借用的密钥或通过entry()API 与拥有的密钥进行。

在您的情况下,get_mut()将返回,None因为您没有在地图中插入任何内容。visited.insert(ROOT, true)会为你做的。


推荐阅读