blog.dopana

Back

Third post in the basic Rust series. In Rust, control flow is not just about choosing paths — many constructs are expressions that produce values.

If and else#

let score = 85;

if score >= 90 {
    println!("Grade: A");
} else if score >= 70 {
    println!("Grade: B");
} else {
    println!("Grade: C");
}
rust

The condition must be a bool — Rust does not coerce numbers to booleans.

If is an expression#

Every branch can return a value. The branches must have the same type:

let grade = if score >= 90 { "A" } else { "B" };
println!("{grade}");
rust

This is often cleaner than a separate assignment.

Loop#

loop repeats forever until you break:

let mut counter = 0;
let result = loop {
    counter += 1;
    if counter == 10 {
        break counter * 2;   // value after break becomes the result
    }
};
println!("{result}");   // 20
rust

While#

let mut n = 3;
while n > 0 {
    println!("{n}");
    n -= 1;
}
rust

For over ranges#

for over a range is the idiomatic way to iterate:

for i in 0..5 {
    println!("{i}");
}
rust

0..5 is exclusive at the end; 0..=5 is inclusive. You can also iterate over collections:

let names = ["Ada", "Grace", "Linus"];
for name in names {
    println!("{name}");
}
rust

Break and continue#

  • break exits the loop immediately.
  • continue skips the rest of the current iteration.
for i in 0..10 {
    if i % 2 == 0 {
        continue;
    }
    if i > 7 {
        break;
    }
    println!("{i}");
}
// prints: 1 3 5 7
rust

Conclusion#

Rust’s control flow is expressive and safe: no truthy/falsy surprises, and branches can produce values. Next in this series: functions.

References#