Search code examples
indexingrusthashmap

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


I have a struct-tuple named Point. It is a 2D cartesian coordinates. I need to use a point as a key in a hashmap but the compiler refuses. How do I approach this?

#[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;

Compiler error is following:

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>`

Solution

  • HashMap does not implement IndexMut. Mutation of entries works through get_mut() with borrowed keys or through the entry() API with owned keys.

    In your case, get_mut() will return None since you have not inserted anything into your map. visited.insert(ROOT, true) will do that for you.