// match是什么?
// match從字面意思來理解就是匹配, 要么匹配要么不匹配.
// 匹配有幾種行為:
// 1. 有或沒有.
// 2. 在不在這個(gè)范圍內(nèi). in
// 3. 是否相等. equal
// 4. 是否為true bool
//
// match pattern 必須是一個(gè)元祖或者結(jié)構(gòu)體, 這是因?yàn)樗麄兌加幸粋€(gè)特性, 成員(Variant).
// 元祖: (1,2,3,4,5,6) 里面的每個(gè)元素都是一個(gè)成員(Variant).
// 結(jié)構(gòu)體: Point {x: 0, y: 10} 其中 x 和 y 是Point里面的成員(Variant).
// Option: Some 和 None 兩個(gè)成員都隸屬于 Option.
fn raise_error_if_match_patterns_not_a_variant() {
let a = String::from("hello");
match a {
String::from("hello") => println!("match true"),
_ => println!("nothing")
}
// error output: not a tuple variant or struct
}
fn tuple_match_is_ok() {
let a = 3;
match a {
1...5 => println!("tuple_match_is_ok: hit"),
_ => println!("nothing")
}
}
fn struct_match_is_ok() {
struct Point {x: i32, y: i32}
let p = Point {x: 10, y: 20};
match p {
Point {x: 10, ..} => println!("struct_match_is_ok: x: hit"),
Point {y: 20, ..} => println!("struct_match_is_ok: y: hit"),
_ => println!("nothing")
}
}
fn option_match_is_ok() {
let a = Some(String::from("hello"));
match a {
Some(ssss) => println!("option_match_is_ok: some: {}", ssss),
None => println!("nothing")
}
}
// match pattern 額外支持判斷條件, 這種情況下不要求每個(gè)對(duì)象必須是成員(Variant).
#[allow(dead_code)]
#[allow(unused_variables)]
fn raise_error_in_match_patterns_using_outer_variable() {
let a = "hello";
let b = Some(String::from("hello"));
match b {
Some(a) => println!("raise_error_using_outer_variable: a: {}", a),
None => println!("nothing")
}
// error output: let a = "hello" never used, consider using `_a` instead.
}
fn match_patterns_using_outer_variable_with_if_statement() {
let a = "hello";
let b = String::from("hello");
match b {
_ if a == b => println!("using_outer_variable: {}", b),
_ => println!("nothing")
}
}
fn main() {
// raise_error_if_match_patterns_not_a_variant();
tuple_match_is_ok();
struct_match_is_ok();
option_match_is_ok();
// raise_error_in_match_patterns_using_outer_variable();
match_patterns_using_outer_variable_with_if_statement()
}
rust--什么是match?
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- @author Jou Email Weibo or Github 0. 預(yù)熱 LCTWebViewControl...
- 學(xué)習(xí)筆記依托于《新求精德語強(qiáng)化教程》,省略了語音部分。直接從第二單元開始,每個(gè)單元分為單詞和語法兩大部分。 Lek...