I'm trying to learn Rust, but the only thing I do is continue to hit the wall, trying to explain to me the familiar (to me) Java concepts in my type system. Or try using Haskell concepts, etc.
I want to write a game with Player and many Resource s. Each Resource can belong to one Player :
struct Player { points: i32, } struct Resource<'a> { owner: Option<&'a Player>, } fn main() { let mut player = Player { points: 0 }; let mut resources = Vec::new(); resources.push(Resource { owner: Some(&player), }); player.points = 30; }
It does not compile, because I cannot specify a resource for the player, at the same time changing it:
error[E0506]: cannot assign to `player.points` because it is borrowed --> src/main.rs:15:5 | 13 | owner: Some(&player), | ------ borrow of `player.points` occurs here 14 | }); 15 | player.points = 30; | ^^^^^^^^^^^^^^^^^^ assignment to borrowed `player.points` occurs here
Also, if the Resource belonged to a mutable Player link, I couldn't even have two Resource with the same owner.
What is the way rust resolves such cases?
I simplified my question, and although Shepmaster's answer is the correct answer, it is not what I wanted to get (because what I asked was not what I really wanted to ask). I will try to rephrase it and add more context.
- Resources are connected in some way - a map of all Resources form a directed graph (un).
- Each player can own many resources, each resource can belong to one player. The player must be able to get points from the resources that they own. I was thinking of a signature, for example:
fn addPoints(&mut self, allResources: &ResourcesMap) -> () . - A player can take a resource associated with one of his resources from another player. This may result in the loss of some points for another player.
Problems:
- How to present such a graph in Rust (possibly a cyclic structure, where each node can point to many nodes)?
- Original problem: if
Resource points to Player , I cannot change the player!
Resource to Player , because a natural way to do this would be to start from some resources of Player A, move through the map to the resource of player B and from that resource to player B to subtract points. It just doesn't seem natural in Rust (at least for me).
source share