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.
学べること
- if, else if, else
- Conditions must be bool
- if as an expression
score = 87
- 1
score >= 90false, skip - 2
score >= 70true - 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.
重要なポイント
- Conditions are checked from top to bottom.
- Only the first true branch runs.
- 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練習
サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。
このレッスンを終えましたか?
学習済みにすると進み具合を記録できます。
進み具合はこのブラウザーに保存されています ログインすると、どのデバイスでも引き継げます。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
すべてのチャレンジ