Matching Values
The match keyword lets you match a value against one or more patterns. The comparisons are done from top to bottom and the first match wins.
C/C++μ switchμ λΉμ·νκ² κ°μ ν¨ν΄μΌλ‘ μ¬μ©ν μλ μμ΅λλ€:
#[rustfmt::skip] fn main() { let input = 'x'; match input { 'q' => println!("Quitting"), 'a' | 's' | 'w' | 'd' => println!("μ΄λ¦¬μ 리 μ΄λ"), '0'..='9' => println!("μ«μ μ λ ₯"), key if key.is_lowercase() => println!("μλ¬Έμ: {key}"), _ => println!("κΈ°ν"), } }
The _ pattern is a wildcard pattern which matches any value. The expressions must be exhaustive, meaning that it covers every possibility, so _ is often used as the final catch-all case.
Match can be used as an expression. Just like if, each match arm must have the same type. The type is the last expression of the block, if any. In the example above, the type is ().
ν¨ν΄μ λ³μ(μ΄ μμμλ key)λ μΌμΉ λΆλ¬Έ λ΄μμ μ¬μ©ν μ μλ λ°μΈλ©μ λ§λλλ€.
μΌμΉ κ°λλ μ‘°κ±΄μ΄ μ°ΈμΈ κ²½μ°μλ§ λΆλΆμ΄ μΌμΉνλλ‘ ν©λλ€.
ν€ ν¬μΈνΈ:
-
ν¨ν΄μμ μ¬μ©λλ νΉμ λ¬Έμλ€μ μλ €μ£ΌμΈμ
|: or κΈ°νΈμ λλ€..: νμν λ§νΌ νμ₯ν©λλ€1..=5: λ κ°(μ¬κΈ°μλ 5)μ ν¬ν¨νλ λ²μλ₯Ό λνλ λλ€_: μμΌλμΉ΄λμ λλ€
-
λ§€μΉ κ°λλ λ³λμ λ¬Έλ² μμλ‘μ ν¨ν΄ μ체λ§μΌλ‘ νννκΈ° μ΄λ €μ΄ 볡μ‘ν κ²½μ°λ₯Ό κ°κ²°νκ² νννκ³ μ ν λ μ μ©ν©λλ€.
-
λ§€μΉμ κ° ν(νΉμ κ°μ§) μμ λ°λ‘
ifλ₯Ό μ¬μ©ν κ²κ³Ό λ€λ¦ λλ€. λ§€μΉ κ°μ§μ=>λ€μ μ¬μ©λifννμμ ν΄λΉ κ°μ§κ° μ νλ λ€μμ μ€νλ©λλ€. λ°λΌμ μ¬κΈ°μifμ‘°κ±΄μ΄ μ€ν¨νλλΌλ μλmatchμ λ€λ₯Έ κ°μ§λ κ³ λ €λμ§ μμ΅λλ€. -
κ°λμ μ μλ 쑰건μ
|λ₯Ό ν¬ν¨νλ ν¨ν΄μ λͺ¨λ ννμμ μ μ©λ©λλ€.