Rust の基礎
Rust Loops: for, while and loop
Three ways to repeat code in Rust, and how break can return a value from loop.
学べること
- for over a range
- while with a condition
- loop with break
for n in 1..=3
1print
2print
3print
4not in range
Three loops for three jobs
Rust has three loops. for visits each item of a range or collection, while repeats as long as a condition is true, and loop repeats until you break out of it.
1..=3 is a range that includes 3; 1..3 would stop at 2. The while loop ends when countdown reaches 0. break total leaves the loop and returns a value, which is stored in result.
重要なポイント
- 1..=3 includes 3; 1..3 stops at 2.
- while repeats as long as the condition is true.
- break value leaves loop and returns the value.
実行できる Rust のサンプル
Rust
main.rs
fn main() {
for n in 1..=3 {
println!("for: {n}");
}
let mut countdown = 3;
while countdown > 0 {
println!("while: {countdown}");
countdown -= 1;
}
let mut total = 0;
let result = loop {
total += 10;
if total >= 30 {
break total;
}
};
println!("loop result: {result}");
}
for: 1
for: 2
for: 3
while: 3
while: 2
while: 1
loop result: 30練習
サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。
このレッスンを終えましたか?
学習済みにすると進み具合を記録できます。
進み具合はこのブラウザーに保存されています ログインすると、どのデバイスでも引き継げます。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
- 打ち上げまでのカウントダウン 指定した数からカウントダウンし、最後に「Liftoff!」を表示します。 簡単
- Sum of Odd Numbers Add every odd number up to a limit. 簡単