Reading — step 1 of 5
Learn
Loops
Rust gives you three loops, each with a job: loop for "until I say stop," while for "while this holds," and for for "over these items" — and then quietly makes for the star by making ranges and iterators the way you express almost everything.
for: the workhorse
for i in 1..=10 { // 1,2,…,10 (..= is INCLUSIVE)
sum += i;
}
for i in 0..10 { // 0,1,…,9 (.. excludes the end)
…
}
The range syntax carries the off-by-one decision in one character: .. excludes the end (perfect for indexing: 0..v.len()), ..= includes it (perfect for "1 to N"). Misreading these two is the entire off-by-one genre in Rust — spend the ten seconds now.
Iterating a collection:
let nums = vec![10, 20, 30];
for n in &nums { // & — borrow, don't consume (chapter 4 explains)
println!("{n}");
}
for (i, n) in nums.iter().enumerate() { // need the index too?
println!("{i}: {n}");
}
Write for n in &nums on autopilot for now; the day the compiler complains about a missing &, the ownership chapter will have made it obvious why.
while: condition loops
let mut n = 1;
while n < 100 {
n *= 2;
}
Nothing exotic — the condition must be a bool, braces required. Use it when the loop is governed by a condition rather than a sequence.
loop: infinite, on purpose — and it returns values
loop {
let line = read_line();
if line == "quit" { break; }
process(line);
}
Rust has a dedicated keyword for infinite loops instead of while true — and gives it a party trick: break can carry a value, making the loop an expression:
let attempts = loop {
tries += 1;
if connect() { break tries; } // the loop evaluates to `tries`
};
"Loop until something works, and hand me what I found" — a pattern that's awkward everywhere else and one line here. continue skips to the next iteration in all three loop kinds.
Your exercise: Sum 1 to N
Read n, sum 1 + 2 + … + n, print the total — the accumulator pattern, Rust edition:
let mut total: i64 = 0;
for i in 1..=n {
total += i;
}
println!("{total}");
Three graded details: the accumulator needs mut (it changes) and must be declared before the loop; the range must be ..=n — plain ..n sums to N−1, the most classic wrong answer this exercise produces; and for large N prefer i64 — n(n+1)/2 outgrows i32 around n≈65,000, and in debug builds Rust will panic on the overflow rather than hide it (which, once you've seen the panic message, you'll agree beats a silently wrong sum).
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…