官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 石河子市| 大田县| 商都县| 包头市| 逊克县| 西盟| 宾阳县| 兴安盟| 关岭| 且末县| 潮安县| 宝丰县| 宁德市| 山阴县| 四会市| 武清区| 乐至县| 梁山县| 巨野县| 江源县| 理塘县| 武邑县| 灵璧县| 宜黄县| 泸西县| 永年县| 海伦市| 安阳市| 吉首市| 清镇市| 碌曲县| 中方县| 衡水市| 淮阳县| 利川市| 乡城县| 慈利县| 清镇市| 灵宝市| 汝州市| 定南县|