- Mastering Rust
- Rahul Sharma Vesa Kaihlavirta
- 396字
- 2021-07-02 13:35:15
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.
- Django+Vue.js商城項目實戰
- Python數據可視化:基于Bokeh的可視化繪圖
- Java高手真經(高級編程卷):Java Web高級開發技術
- 數據結構習題精解(C語言實現+微課視頻)
- Ray分布式機器學習:利用Ray進行大模型的數據處理、訓練、推理和部署
- Silverlight魔幻銀燈
- C# 8.0核心技術指南(原書第8版)
- RabbitMQ Cookbook
- Protocol-Oriented Programming with Swift
- SSM開發實戰教程(Spring+Spring MVC+MyBatis)
- Spring MVC+MyBatis開發從入門到項目實踐(超值版)
- 細說Python編程:從入門到科學計算
- 智能手機故障檢測與維修從入門到精通
- Microsoft Dynamics GP 2013 Cookbook
- Python機器學習