Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

while

while キーワードは、条件が真である間ループを実行するために使用できます。

悪名高い FizzBuzzwhile ループを使って書いてみましょう。

fn main() {
    // カウンター変数
    let mut n = 1;

    // `n` が 101 未満である間ループする
    while n < 101 {
        if n % 15 == 0 {
            println!("fizzbuzz");
        } else if n % 3 == 0 {
            println!("fizz");
        } else if n % 5 == 0 {
            println!("buzz");
        } else {
            println!("{}", n);
        }

        // カウンターをインクリメント
        n += 1;
    }
}