this post was submitted on 25 Mar 2024
8 points (100.0% liked)

Rust

6029 readers
2 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 1 year ago
MODERATORS
 

I have a struct that looks like this:

pub struct Game {
    /// A HashSet with the players waiting to play as account strings.
    lobby: HashSet<String>,
    /// capacity determines  how many people a match contains.
    capacity: u8,
    /// A vector of ongoing matches.
    matches: Vec<Match>,
    /// HashSet indicating for each player which match they are in.
    players: HashMap<String, usize>,
}

I realised that this won't work because if there are 3 matches (0, 1, 2) and I remove 1 because it ends, the players that used to point at 2 will be pointing outside the vector or to an incorrect match.

So I thought the obvious solution was to use a reference to the match: players: HashMap<String, &Match>. But this makes lifetimes very complicated.

What's a good way to deal with a case like these where data are interrelated in the same struct?

you are viewing a single comment's thread
view the rest of the comments
[–] expr@programming.dev 7 points 8 months ago (1 children)

Could you not have a hashmap keyed on matches pointing to vectors of strings for the players in each match? Basically modeling the data how you want rather than relying on indexing.

[–] modulus@lemmy.ml 1 points 8 months ago (1 children)

Not sure I understand. What I'm trying to do is something like this:

  • Poll a stream which takes fedi events. Read player commands.
  • If an event comes from a known player, check which match they are into.
  • With that info, get their opponents/coplayers etc and perform the change of state in the game (send replies, next turn, etc).

So what I have as a key is a player name (AP username) and from that I need to find which match they're in.

There's nothing semantically useful about a match ID.

[–] expr@programming.dev 2 points 8 months ago

If you instead made your lobby field a HashMap<String, MatchId>, then whenever you get an event from a known player, you can lookup the match they are in from the lobby map and use that to lookup other data about the match (such as the other players) via the matches field (assuming that was also changed to be a hashmap as described in my previous comment).