match ํ‘œํ˜„์‹

matchํ‚ค์›Œ๋“œ๋Š” ์–ด๋–ค ๊ฐ’์„ ํ•˜๋‚˜ ์ด์ƒ์˜ ํŒจํ„ด์— ๋Œ€ํ•ด ๋งค์น˜ํ•˜๋Š”๋ฐ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋Ÿฐ ๋ฉด์—์„œ if let ํ‘œํ˜„์‹์„ ์—ฌ๋Ÿฌ๊ฐœ ์ด์–ด ๋†“์€ ๊ฒƒ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค:

fn main() {
    match std::env::args().next().as_deref() {
        Some("cat") => println!("Will do cat things"),
        Some("ls")  => println!("Will ls some files"),
        Some("mv")  => println!("Let's move some files"),
        Some("rm")  => println!("Uh, dangerous!"),
        None        => println!("Hmm, no program name?"),
        _           => println!("Unknown program name!"),
    }
}

if let๊ณผ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ๋งค์น˜์˜ ๋ชจ๋“  ํŒ”(arm)์€ ๊ฐ™์€ ํƒ€์ž…์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ํŒ”์ด ๋ธ”๋ก์ด๋ผ๋ฉด ๋ธ”๋ก์˜ ๋งˆ์ง€๋ง‰ ํ‘œํ˜„์‹์ด ๊ทธ ํƒ€์ž…์ด ๋ฉ๋‹ˆ๋‹ค. ์œ„์˜ ์˜ˆ์ œ์—์„œ ๋งค์น˜ ํ‘œํ˜„์‹์˜ ํƒ€์ž…์€ ()์ž…๋‹ˆ๋‹ค.

ํŒจํ„ด์— ๊ด€ํ•œ ์„ค๋ช…์€ ํŒจํ„ด ๋งค์นญ์„ ์ฐธ์กฐํ•˜์„ธ์š”.

  • match ํ‘œํ˜„์‹์„ ๋ณ€์ˆ˜์— ํ• ๋‹นํ•˜๊ณ  ๊ทธ ๊ฐ’์„ ์ถœ๋ ฅํ•ด๋ณด์„ธ์š”.
  • .as_deref()๋ฅผ ์ง€์›Œ๋ณด๊ณ , ์ด ๋•Œ ๋‚˜์˜ค๋Š” ์—๋Ÿฌ๋ฅผ ์„ค๋ช…ํ•ด์ฃผ์„ธ์š”.
    • std::env::args().next()๋Š” Option<String> ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋Š”๋ฐ, String์€ ์ง์ ‘ ๋งค์น˜ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.
    • as_deref()๋Š” Option<T>๋ฅผ Option<&T::Target>์œผ๋กœ ๋ฐ”๊ฟ”์ค๋‹ˆ๋‹ค. ์ด ๊ฒฝ์šฐ๋Š” Option<String>์—์„œ Option<&str>๋กœ ๋ฐ”๋€๋‹ˆ๋‹ค.
    • ์ด์ œ๋Š” ํŒจํ„ด ๋งค์นญ์œผ๋กœ Option ์•ˆ์˜ &str์„ ๋งค์น˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.