-2

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>`
Stargateur
  • 24,473
  • 8
  • 65
  • 91
ArekBulski
  • 4,520
  • 4
  • 39
  • 61
  • 2
    you could read the documentation of hashmap :p https://doc.rust-lang.org/std/collections/struct.HashMap.html – Stargateur Apr 09 '21 at 13:03
  • 2
    Does this answer your question? [How can I update a value in a mutable HashMap?](https://stackoverflow.com/questions/30414424/how-can-i-update-a-value-in-a-mutable-hashmap) – Stargateur Apr 09 '21 at 13:06
  • 2
    @Stargateur I would say that this is not a good dup, the current question is about adding a value to a map, while your linked question is about updating a value already present. – mcarton Apr 09 '21 at 13:09

1 Answers1

3

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.

sebpuetz
  • 2,430
  • 1
  • 7
  • 15