Start with the idea
match forces every variant to be handled, so adding a new state turns every incomplete match into a compile error instead of a silent bug. Variants can carry data, which lets one type model a whole state machine rather than a bag of loosely related fields.
A boolean can distinguish two states, but it becomes obscure when a feature has several states or each state carries different data. An enum names the alternatives. Message::Quit carries nothing, Message::Move carries two coordinates, and Message::Write carries text. A value is exactly one variant at a time, so code cannot accidentally pair coordinates with a quit message as it might with a loose struct of optional fields.
A match examines the variant and binds only the data available in that branch. Every arm must produce a compatible type if the match is used as an expression. The compiler's exhaustiveness check is valuable during maintenance: adding Message::Resize points to every decision that now needs a policy.
Keep learning, for free
The rest of this lesson is waiting for you.
Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.
No payment details. Your account opens the complete Academy.