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
์ ๋ค๋ฅธ ๊ฐ์ง๋ ๊ณ ๋ ค๋์ง ์์ต๋๋ค. -
๊ฐ๋์ ์ ์๋ ์กฐ๊ฑด์
|
๋ฅผ ํฌํจํ๋ ํจํด์ ๋ชจ๋ ํํ์์ ์ ์ฉ๋ฉ๋๋ค.