Rust の基礎

Rust if, else if and else

Run code only when a condition is true, and use if as an expression that returns a value.

  • 初級
  • 約2分で読めます
  • 実行できるサンプル 1 件
学べること
  • if, else if, else
  • Conditions must be bool
  • if as an expression
score = 87
  1. 1score >= 90false, skip
  2. 2score >= 70true
  3. 3"Good"this branch runs

The first true branch runs

An if statement runs a block only when its condition is true. The condition must be a bool: Rust does not treat numbers as true or false.

The conditions are checked from top to bottom and only the first true branch runs, so 87 prints Good. Because if is an expression, it can produce a value for let: every branch must then return the same type.

重要なポイント

  1. Conditions are checked from top to bottom.
  2. Only the first true branch runs.
  3. let grade = if ... { 'A' } else { 'B' }; stores the result.

実行できる Rust のサンプル

Rust
コードを実行 →
main.rs
fn main() {
    let score = 87;

    if score >= 90 {
        println!("Excellent");
    } else if score >= 70 {
        println!("Good");
    } else {
        println!("Keep practicing");
    }

    let grade = if score >= 90 { 'A' } else if score >= 80 { 'B' } else { 'C' };
    println!("Grade: {grade}");
}
この例の実行ボタンを作成 実行結果
Good
Grade: B

練習

サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。

このレッスンを終えましたか?

学習済みにすると進み具合を記録できます。

次へ: FizzBuzz →

チャレンジで練習する

このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。

すべてのチャレンジ