lundi 4 septembre 2023

What is an idiomatic equivalent of simultaneously mutably and immutably borrowing sibling struct feilds in Rust? [duplicate]

I have a single game state struct - a monolith struct that has 2 feilds: a map, and a list of players. To update the player positions, I want a function that takes an immutable reference to the map, and a mutable reference to the vector of players. But when I attempt this, the borrow checker disallows it because I cannot borrow the monolith game state immutably and immutably at the same time.

My current solution is stuffing the players and map into RefCells, each of which I can mutable borrow. Is there a more idiomatic solution, where I keep the monolith struct, but can still use functions that interop with its fields with a mix of mutable and immutable borrows?

I tried passing in the whole game state, but this loses the granularity of the original function. Splitting the struct up has the disadvantage of needing explicit coupling, so I'd like to avoid breaking up my struct if possible. And lastly, using RefCells everywhere seems like a bandaid solution, and I am concerned that it is more error-prone due to possible panic scenarios which RefCells introduce.

Aucun commentaire:

Enregistrer un commentaire