How to represent shared mutable state?

后端 未结 2 1783
滥情空心
滥情空心 2020-12-03 22:36

I\'m trying to learn Rust, but the only thing I do is keep hitting the wall trying to shoehorn familiar (to me) Java concepts into its type system. Or try to shoehorn Haskel

2条回答
  •  误落风尘
    2020-12-03 23:02

    Each Resource can be owned by one Player.

    Make the types do that then:

    struct Player {
        points: i32,
        resources: Vec,
    }
    
    struct Resource {
        gold: i32,
    }
    
    fn main() {
        let player1 = Player {
            points: 30,
            resources: vec![Resource { gold: 54 }],
        };
        let player2 = Player {
            points: 50,
            resources: vec![Resource { gold: 99 }],
        };
    
        // If you really need an array of all the resources...
        // Although this seems like you should just ask the Player to do something
        let mut resources: Vec<_> = vec![];
        resources.extend(player1.resources.iter());
        resources.extend(player2.resources.iter());
    }
    

    Edit Thanks to @ziggystar for pointing out my original version allowed players to only have one Resource. Now players may own N resources, but they still are the only owner of a resource.

提交回复
热议问题