Expand description
Control flow based on pattern matching.
match can be used to run code conditionally. Every pattern mustbe handled exhaustively either explicitly or by using wildcards like_ in thematch. Sincematch is an expression, values can also bereturned.
letopt = Option::None::<usize>;letx =matchopt {Some(int) => int,None=>10,};assert_eq!(x,10);leta_number = Option::Some(10);matcha_number {Some(x)ifx <=5=>println!("0 to 5 num = {x}"),Some(x @6..=10) =>println!("6 to 10 num = {x}"),None=>panic!(),// all other numbers_=>panic!(),}match can be used to gain access to the inner members of an enumand use them directly.
enumOuter { Double(Option<u8>,Option<String>), Single(Option<u8>), Empty}letget_inner = Outer::Double(None,Some(String::new()));matchget_inner { Outer::Double(None,Some(st)) =>println!("{st}"), Outer::Single(opt) =>println!("{opt:?}"),_=>panic!(),}For more information onmatch and matching in general, see theReference.