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)λŠ” 일치 λΆ€λ¬Έ λ‚΄μ—μ„œ μ‚¬μš©ν•  수 μžˆλŠ” 바인딩을 λ§Œλ“­λ‹ˆλ‹€.

일치 κ°€λ“œλŠ” 쑰건이 참인 κ²½μš°μ—λ§Œ 뢀뢄이 μΌμΉ˜ν•˜λ„λ‘ ν•©λ‹ˆλ‹€.

This slide should take about 10 minutes.

ν‚€ 포인트:

  • νŒ¨ν„΄μ—μ„œ μ‚¬μš©λ˜λŠ” 특수 λ¬Έμžλ“€μ„ μ•Œλ €μ£Όμ„Έμš”

    • |: or κΈ°ν˜Έμž…λ‹ˆλ‹€
    • ..: ν•„μš”ν•œ 만큼 ν™•μž₯ν•©λ‹ˆλ‹€
    • 1..=5: 끝 κ°’(μ—¬κΈ°μ„œλŠ” 5)을 ν¬ν•¨ν•˜λŠ” λ²”μœ„λ₯Ό λ‚˜νƒ€λƒ…λ‹ˆλ‹€
    • _: μ™€μΌλ“œμΉ΄λ“œμž…λ‹ˆλ‹€
  • 맀치 κ°€λ“œλŠ” λ³„λ„μ˜ 문법 μš”μ†Œλ‘œμ„œ νŒ¨ν„΄ 자체만으둜 ν‘œν˜„ν•˜κΈ° μ–΄λ €μš΄ λ³΅μž‘ν•œ 경우λ₯Ό κ°„κ²°ν•˜κ²Œ ν‘œν˜„ν•˜κ³ μž ν•  λ•Œ μœ μš©ν•©λ‹ˆλ‹€.

  • 맀치의 각 νŒ”(ν˜Ήμ€ κ°€μ§€) μ•ˆμ— λ”°λ‘œ ifλ₯Ό μ‚¬μš©ν•œ 것과 λ‹€λ¦…λ‹ˆλ‹€. 맀치 κ°€μ§€μ˜ => 뒀에 μ‚¬μš©λœ if ν‘œν˜„μ‹μ€ ν•΄λ‹Ή κ°€μ§€κ°€ μ„ νƒλœ λ‹€μŒμ— μ‹€ν–‰λ©λ‹ˆλ‹€. λ”°λΌμ„œ μ—¬κΈ°μ„œ if 쑰건이 μ‹€νŒ¨ν•˜λ”λΌλ„ μ›λž˜ match의 λ‹€λ₯Έ κ°€μ§€λŠ” κ³ λ €λ˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.

  • κ°€λ“œμ— μ •μ˜λœ 쑰건은 | λ₯Ό ν¬ν•¨ν•˜λŠ” νŒ¨ν„΄μ˜ λͺ¨λ“  ν‘œν˜„μ‹μ— μ μš©λ©λ‹ˆλ‹€.