1 comment

[ 2.5 ms ] story [ 7.1 ms ] thread
> You write a `TrafficLight` struct. You use an `enum` for state. You might use a Mutex. The compiler ensures you don’t access the memory of a deleted light. But does it ensure NS and EW aren’t green simultaneously? No. That’s a logic error, not a memory error. Rust saves you from a segfault, but it happily compiles a crash.

But Rust's type system still lets you build a system that covers that logic error. Don't do the naive thing (two lights as enums with states of Red or Green which permits four states, one of which is invalid). Create a four state enum: RG, GR, RR->GR, RR->RG (the third and fourth look superficially the same but indicate which light will become green in the next state transition). You could also do three states (RG, GR, RR) but then you need to track additional state to know which light was green and which will become green, which is neatly encapsulated in the four state machine. There, logic error removed from the program and within Rust's type system.

If you don't want both lights to be red at the same time, then you just do it with two states: RG, GR. Now it's impossible to get into the state where both lights are green because that state doesn't exist and you don't need a guard to prevent it, it literally cannot happen in the code.