I'm going through Mazes for Programmers and thought I'd try to do it in Rust (the original code is in Ruby).
One of the first things you do in the book is to implement a Cell
class that includes links to other cells. Naively, I thought I'd be able to do something like this:
pub struct Cell {
row: u32,
column: u32,
links: HashMap<Box<Cell>, bool>,
}
The idea being that each Cell
in a maze knows what other cells it connects to, and that a Maze
is just a collection of Cells
. 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.
Specifically, I cannot figure out how to implement link
here:
impl Cell {
pub fn new (row: u32, column: u32) -> Cell {
return Cell {
row: row,
column: column,
links: HashMap::new(),
};
}
pub fn link(&mut self, other: &mut Cell, bidi: bool) {
self.links.insert(Box::new(other), true); // cannot get anything even remotely like this to work here.
}
}
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.
I think that I want each Cell
struct to maintain (via an embedded HashMap
) a reference (in the non-explicit use of the term) to other Cells
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 Rc
or something similar.
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 Cell
structs entirely in favor of something more direct like a big HashMap
of tuples.