dyllandry / ladders-and-slides

Everyone's favourite boardgame, ladders and slides! 🪜
0 stars 0 forks source link

WIP: add board struct #2

Closed dyllandry closed 1 year ago

dyllandry commented 1 year ago

The situation is I have Tiles that have i32 positions, and Connections that contain two references start and end that both reference tiles. The Board struct contains tiles and connections.

I added lifetime annotations so that the connections and their tile references live as long as the board. And since the board contains the tiles, I thought that would satisfy the borrow checker by saying: "Hey look, the connections need the tiles it references to live as long as 'a, and the board itself lives for 'a and contains the tiles itself, so we're good!

But I get these 3 errors on line 80 that I don't understand:

 │   Error  cannot move out of `board` because it is borrowed, move out of `board` occurs here rustc (E0505) [80, 9]
 │   Error  cannot move out of `board` because it is borrowed, returning this value requires that `board.tiles` is borrowed for `'a` rustc (E0505) [80, 9]
 │   Error  cannot return value referencing local data `board.tiles`, returns a value referencing data owned by the current function rustc (E0515) [80, 9]
 │   Tip  lifetime `'a` defined here rustc (E0505) [6, 6]
 │   Tip  borrow of `board.tiles` occurs here rustc (E0505) [31, 28]
 │   Tip  `board.tiles` is borrowed here rustc (E0515) [31, 28]
 │   Tip  `board.tiles` is borrowed here rustc (E0515) [42, 28]
 │   Tip  `board.tiles` is borrowed here rustc (E0515) [58, 28]
 │   Tip  `board.tiles` is borrowed here rustc (E0515) [69, 28]

In response to "Returning this value requires that board.tiles is borrowed for 'a, isn't that okay? I know it should. The connections borrow tiles for 'a. Isn't that okay?

dyllandry commented 1 year ago

Does it have something to do with the fact that board.tiles is a Vec<Tile> which means tiles could be removed from that list which would mean the tile references in each connection are not guaranteed to stay valid? Like there's nothing stopping me from filling board.tiles with tiles, then referencing those tiles in a bunch of connections, then deleting all the tiles from board.tiles. That would leave a bunch of dangling references in those connections.

dyllandry commented 1 year ago

I found an SO question about it: https://stackoverflow.com/questions/40875152/reference-to-element-in-vector

dyllandry commented 1 year ago

I think I solved the problem following the SO answer, using Rc for board.tiles, as well as the tile in each pawn and the two tiles in each connection.

This PR tracks this new approach: https://github.com/dyllandry/ladders-and-slides/pull/3