if let ํ‘œํ˜„์‹

if let ํ‘œํ˜„์‹์„ ์‚ฌ์šฉํ•˜๋ฉด ๊ฐ’์ด ํŒจํ„ด๊ณผ ์ผ์น˜ํ•˜๋Š”์ง€์— ๋”ฐ๋ผ ๋‹ค๋ฅธ ์ฝ”๋“œ๋ฅผ ์‹คํ–‰ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค:

fn main() {
    let arg = std::env::args().next();
    if let Some(value) = arg {
        println!("Program name: {value}");
    } else {
        println!("Missing name?");
    }
}

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

  • if let์ด match๋ณด๋‹ค ๋” ๊ฐ„๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค(์˜ˆ: ํ•œ๊ฐ€์ง€ ๋ธŒ๋žœ์น˜๋งŒ ํฅ๋ฏธ๋กœ์šด ๊ฒฝ์šฐ). ์ด์™€ ๋‹ฌ๋ฆฌ match์—์„œ๋Š” ๋ชจ๋“  ๋ธŒ๋žœ์น˜๊ฐ€ ์ฒ˜๋ฆฌ๋˜์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

  • ์ผ๋ฐ˜์  ์‚ฌ์šฉ๋ฒ•์€ Option์„ ์‚ฌ์šฉํ•  ๋•Œ Some ๊ฐ’์„ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

  • match์™€ ๋‹ฌ๋ฆฌ if let์€ ํŒจํ„ด ์ผ์น˜๋ฅผ ์œ„ํ•œ ๋ณดํ˜ธ ์ ˆ์„ ์ง€์›ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

  • 1.65๋ถ€ํ„ฐ ์œ ์‚ฌํ•œ let-else ๊ตฌ์„ฑ์€ ๋””์ŠคํŠธ๋Ÿญ์ฒ˜๋ง ํ• ๋‹น์„ ์‹คํ–‰ํ•˜๊ฑฐ๋‚˜ ์‹คํŒจํ•  ๊ฒฝ์šฐ ๋ฐ˜ํ™˜๋˜์ง€ ์•Š๋Š” ๋ธ”๋ก ๋ธŒ๋žœ์น˜(panic/return/break/continue)๋ฅผ ๋ณด์œ ํ•˜๋„๋ก ํ—ˆ์šฉํ•ฉ๋‹ˆ๋‹ค:

    fn main() {
        println!("{:?}", second_word_to_upper("foo bar"));
    }
     
    fn second_word_to_upper(s: &str) -> Option<String> {
        let mut it = s.split(' ');
        let (Some(_), Some(item)) = (it.next(), it.next()) else {
            return None;
        };
        Some(item.to_uppercase())
    }