Git repo: https://github.com/caveofprogramming/rust/
The match
keyword enables us to apply patterns to an object, to see if it matches any of the patterns. Rust will work down the arms of the match
statement until it finds one that matches.
The matches must be exhaustive, so that it’s not possible for a match to not be found.
match
can be used as a statement, or as an expression.
Match Expressions
Here I’ll use it to retrieve the value from an Option
enum
.
This code sets result to 5.
If I try the match
on number2
instead, I get 0
.
Notice the commented-out underscore. This can be used to catch any values that aren’t matched by any of the previous arms of match
.
All the arms of match
here must return a value of the same type; i32
in this case.
Match Statements
match can also be used as a statement, to run code blocks or functions.
This code creates a Point
enum
and then declares a variable which we can make refer to any of the Point
enum
constants.
The match
statement then runs different code depending on the precise type of the point
variable.
Here I’ve only checked for Point1D
and Point2D
. If the point variable refers to anything else (which in this case would have to be a Point3D
), the other
arm executes.
This seems to be virtually the same as using an _
to match any remaining possibilities, except that it allows you to get a references to the object that wasn’t matched. There doesn’t seem to be anything special about the word “other”. We can use different variable names here and it works fine.
Here I’ve turned on debug printing on Point
, then we can run a function to print it if it doesn’t match.
In this case the return type of all the match
arms is Unit
, ()
. I’ve used semi-colons after the println
macro to ensure this (since I don’t know what println
returns).