Hitting `thread 'main' has overflowed its stack` error

With the below code I'm hitting the (in)famous error:

thread 'main' has overflowed its stack.

I'm trying to refactor my database layer code following some sort of "data-oriented-design" using HashMap instead of big structs with nested Box<>.

But I cannot change the service layer which still uses the structs with Box<> as you can see (and I need to convert).

REPRODUCTION: undefined | Rust Explorer

This is the code that I think is throwing:

struct Store {
    pub players: HashMap<String, DBPlayer>,
    pub teams: HashMap<String, DBTeam>,
}

impl Store {
    pub fn to_domain_team(&self, id: &str) -> Team {
        let team = self.teams.get(id).unwrap();

        Team {
            id: team.id.to_string(),
            name: team.name.to_string(),
            players: if self.players.is_empty() {
                None
            } else {
                Some(
                    self.players
                        .keys()
                        .map(|id| self.to_domain_player(id))
                        .collect(),
                )
            },
        }
    }

    pub fn to_domain_player(&self, id: &str) -> Player {
        let player = self.players.get(id).unwrap();

        Player {
            id: player.id.to_string(),
            name: player.name.to_string(),
            team_id: player.team_id.to_string(),
            team: self
                .teams
                .contains_key(&player.team_id)
                .then(|| Box::new(self.to_domain_team(&player.team_id))),
        }
    }
}

As you can see I think the issue is that a team creates players which in turn create it thus continuing indefinitely!

Is there a way to fix this?

You need to choose, either Team owns the Players or a Player owns its own Team, otherwise you'll try to create an infinite structure. Though a better design would probably represent Team and Player as some struct with a reference to the Store and a key/reference to the relevant hashmap data

2 Likes

Can you please write an example of what you mean?

Please add cross-posts as links to your question to avoid duplicated effort:

2 Likes

Something like:

struct Player<'store> {
    db_player: &'store DBPlayer,
    team : &'store DBTeam,
}

And likewise for Team.

Note though that this is supposed to be a temporary view of a player/team. Don't try to store this in the long term or you'll likely end up with some (unsolvable without refactoring) lifetime error.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.