I'm curious about the history of this. I would assume switch
would appeal to C/C++/Java/etc programmers and thus be a natural choice. If one wanted to avoid confusion in semantics (since match
is more powerful than switch
) I'd assume one would borrow case
from Haskell instead.
It is mainly used in a menu-driven program where the user selects which function they want to run. A switch case in Rust is achieved by the keyword match.
Match is similar to a switch statement but it is a lot more powerful. A match works on integers, ranges of integers, bools, enums, tuples, arrays and structs. It will destructure tuples, arrays and structs. It requires a default handler if necessary.
Rust has an extremely powerful control-flow operator called match that allows us to compare a value against a series of patterns and then execute code based on which pattern matches.
match and switch are just convenient ways of writing long if-else statements for increasing readability and making code more robust etc. Usually, match is used for pattern matching and also it can be a statement and as well as expression whereas switch is used for equality checking and is statement only.
The Rust Reference cites Standard ML (SML) and OCaml as an influence for pattern matching. In OCaml, pattern matching uses the match
keyword.
The original Rust compiler was written in OCaml, so it makes sense that OCaml would have had a stronger influence on Rust than, say, Haskell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With