Rust:不能使用 HashMap::<Point,bool>

Rust: cannot use HashMap::<Point,bool>

我有一个名为 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>`

HashMap 未实现 IndexMut。条目的变异通过 get_mut() 使用借来的密钥或通过 entry() API 使用拥有的密钥。

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