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์˜ ๋‹ค๋ฅธ ๊ฐ€์ง€๋Š” ๊ณ ๋ ค๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

  • ๊ฐ€๋“œ์— ์ •์˜๋œ ์กฐ๊ฑด์€ | ๋ฅผ ํฌํ•จํ•˜๋Š” ํŒจํ„ด์˜ ๋ชจ๋“  ํ‘œํ˜„์‹์— ์ ์šฉ๋ฉ๋‹ˆ๋‹ค.