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

if/else

if-else による分岐は他の言語と似ています。それらの多くとは異なり、 真偽値の条件を括弧で囲む必要はなく、各条件の後にはブロックが続きます。 if-else 条件分岐は式であり、 すべての分岐は同じ型を返さなければなりません。

fn main() {
    let n = 5;

    if n < 0 {
        print!("{} is negative", n);
    } else if n > 0 {
        print!("{} is positive", n);
    } else {
        print!("{} is zero", n);
    }

    let big_n =
        if n < 10 && n > -10 {
            println!(", and is a small number, increase ten-fold");

            // この式は `i32` を返します。
            10 * n
        } else {
            println!(", and is a big number, halve the number");

            // この式も `i32` を返さなければなりません。
            n / 2
            // TODO ^ この式をセミコロンで抑制してみてください。
        };
    //   ^ ここにセミコロンを置くのを忘れないでください!すべての `let` 束縛にはセミコロンが必要です。

    println!("{} -> {}", n, big_n);
}