Hi!
So, for learning purposes I'm trying to model a "maze" structure. A Maze
is a collection of Room
s. Each Room
object has an unique id and an array of adjacent rooms.
I've defined the Maze
as having a vector or Reference Counted RefCells of Room
s, so that each room can be shared and modified.
The room has an array of 4 Optional neighbour-rooms, each being a reference to one of the other Rooms stored in the Maze vector.
You can see it in action here
I'm aware that this could be simplified by simply storing for each room an array of ids, but again, I'm studying Rust and I want a better understanding of references, lifetimes, borrowing.
The problem arises in the constructor the Maze
struct where I loop each room and apply some logic (skipped in the pasted example as it doesn't really add anything to the problem) to find suitable neighbours and fill the room's neighbour array accordingly.
The code doesn't work. The first problem is that within the constructor function iterating the rooms object takes ownership of it and so I cannot associate it to the .rooms
property of the Maze
I am initializing.
The second problem is that looking for a room actually takes ownership of it and I don't know how to express "ok, this room is suitable as a neighbour, now only give me a reference to it and forget about about the actual room altogether".
Any help on how to overcome these two errors? Also, does my use of Rc
, RefCell
, Option
, references make sense? Thanks!