loop ํ‘œํ˜„์‹

๋งˆ์ง€๋ง‰์œผ๋กœ, ๋ฌดํ•œ ๋ฃจํ”„๋ฅผ ๋งŒ๋“œ๋Š” loop ํ‚ค์›Œ๋“œ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.

๋”ฐ๋ผ์„œ ๋ฐ˜๋“œ์‹œ break ๋˜๋Š” return์„ ์‚ฌ์šฉํ•ด์„œ ๋ฃจํ”„๋ฅผ ์ •์ง€ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค:

fn main() {
    let mut x = 10;
    loop {
        x = if x % 2 == 0 {
            x / 2
        } else {
            3 * x + 1
        };
        if x == 1 {
            break;
        }
    }
    println!("Final x: {x}");
}
  • loop๋ฅผ ๊ฐ’(์˜ˆ: break 8)์œผ๋กœ ๋‚˜๋ˆ„๊ณ  ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.
  • loop๋Š” non-trivial ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ์œ ์ผํ•œ ๋ฐ˜๋ณต๋ฌธ์ž…๋‹ˆ๋‹ค. ์ด๋Š” while ๋ฐ for ๋ฐ˜๋ณต๋ฌธ๊ณผ ๋‹ฌ๋ฆฌ ์ตœ์†Œํ•œ ํ•œ ๋ฒˆ์€ ๋ฃจํ”„๋ฌธ์„ ์ˆ˜ํ–‰ํ•˜๋Š” ๊ฒƒ์ด ๋ณด์žฅ๋˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.