8414 shaares
200 private links
200 private links
One approach for achieving compile-time checks, might be having two different structs for alive and dead player, and have the necessary methods implemented for them respectively.
why it’s bad:
- the API is not clean. We are storing the same fields in both Dead and Alive player, while they are both just Players.
- the end-user has to know when to create an instance of Alive player and Dead player. It might be simple to guess in this example, but imagine much more complex/abstract types. If possible, our API should be responsible for when to use which type, not the end user.
Solution 3 is better with an struct that uses a state! The state determines how is the player and different functions are implemented for a player state.
Note it is similar to typescript with an interface or type such as Player<'alive'>
of type Player<T> = { state: T, ...}