I’ve spent some time developing a new project in rust.
I have a problem understanding whether I am using a Cell in the right way.
This is my current problem, generalized.
I need access to a struct World, which has ownership over some Resources.
In particular I need (mut) references to the resources. The problem arises when I need mutable access to a resource (requiring &mut World) and a non-mut reference (requiring &World). I cant get such references together as I would violate Rust’s reference rules.
The way I’d like to tackle this is by using a Cell.
I have this code in my project:
fn take_world(&self, func: impl FnOnce(World) -> World) {
let state = self.state_ref();
let world = state.world
.take();
let world = func(world);
state.world
.replace(world);
}
This should let me take the World from the cell, do what I need with the FnOnce, and the automatically replace it.
Do you think this is a good approach? Could it be considered a code smell?
Other solutions might include code refactor, but the World/Resource part come from a library so I cant do much about it.