title: How can I create a struct with a HashMap where the keys the same type as the container
body: <p>I'm going through <a href="https://pragprog.com/book/jbmaze/mazes-for-programmers" rel="nofollow noreferrer">Mazes for Programmers</a> and thought I'd try to do it in Rust (the original code is in Ruby).</p>
  
  <p>One of the first things you do in the book is to implement a <code>Cell</code> class that includes links to other cells. Naively, I thought I'd be able to do something like this:</p>
  
  <pre><code>pub struct Cell {
      row: u32,
      column: u32,
  
      links: HashMap&lt;Box&lt;Cell&gt;, bool&gt;,
  }
  </code></pre>
  
  <p>The idea being that each <code>Cell</code> in a maze knows what other cells it connects to, and that a <code>Maze</code> is just a collection of <code>Cells</code>. Unfortunately, this leads one into the doubly-linked-list problem of Rust's borrowing and ownership semantics, and I'm not sure how to get around this. </p>
  
  <p>Specifically, I cannot figure out how to implement <code>link</code> here:</p>
  
  <pre><code>impl Cell {
      pub fn new (row: u32, column: u32) -&gt; Cell {
          return Cell {
              row: row,
              column: column,
              links: HashMap::new(),
          };
      }
  
      pub fn link(&amp;mut self, other: &amp;mut Cell, bidi: bool) {
          self.links.insert(Box::new(other), true); // cannot get anything even remotely like this to work here.
      }
  }
  </code></pre>
  
  <p>I took a look at the Rust Book's section on choosing your guarantees, which has some good info on one's respective choices of pointer-wrappers and abstractions, but I'm really not sure how to reason about what I'd like to do with the compiler. </p>
  
  <p>I think that I want each <code>Cell</code> struct to maintain (via an embedded <code>HashMap</code>) a reference (in the non-explicit use of the term) to other <code>Cells</code> that it is connected to, but since that link will be bi-directional it seems to me that I'm going to end up using <code>Rc</code> or something similar. </p>
  
  <p>It's also possible that I should just take a step away from the literal translation of the Ruby code in the book and think about a more idiomatic approach -- possibly ignoring the issue of <code>Cell</code> structs entirely in favor of something more direct like a big <code>HashMap</code> of tuples. </p>