Match expressions

Rust's match expressions are quite a joy to use. It's basically C's switch statement on steroids and allows you to make decisions, depending on what value the variable has and whether it has advanced filtering capabilities. Here's a program that uses match expressions:

// match_expression.rs

fn req_status() -> u32 {
200
}

fn main() {
let status = req_status();
match status {
200 => println!("Success"),
404 => println!("Not Found"),
other => {
println!("Request failed with code: {}", other);
// get response from cache
}
}
}

In the preceding code, we have a  req_status, function that returns a dummy HTTP request status code of 200, which we call in main and assign to status. We then match on this value using the match keyword, followed by the variable we want to check the value of (status), followed by a pair of braces. Within braces, we write expressions – these are called match arms. These arms represent the possible values that the variable being matched can take. Each match arm is written by writing the possible value of the variable, followed by a =>, and then the expression on the right. To the right, you can either have a single line expression or a multi-line expression within {} braces. When written in a single line expression, they need to be delimited with a comma. Also, every match arm must return the same type. In this case, each match arm returns a Unit type ().

Another nice feature or you can call guarantee of match expressions is that we have to match exhaustively against all possible cases of the value we are matching against. In our case, this would be listing all the numbers up until the maximum value of i32. However, practically, this is not possible, so Rust allows us to either ignore the rest of the possibilities by using a catch all variable (here, this is other) or an _ (underscore) if we want to ignore the value. Match expressions are a primary way to make decisions around values when you have more than one possible value and they are very concise to write. Like if else expressions, the return value of a match expression can also be assigned to a variable in a let statement when it's delimited with a semicolon, with all match arms returning the same types.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset