Control Flow
Control flow in Rust uses if/else if/else statements, but with one important difference: the condition must be a boolean. You can't use numbers or other types as conditions like you can in some other languages. This helps prevent bugs.
One cool thing about if in Rust is that it can be used as an expression. This means you can assign the result of an if/else block to a variable. For example, let x = if condition { 5 } else { 6 }; is valid Rust code.
For loops in Rust come in different flavors. The loop keyword creates an infinite loop, while while loops continue as long as a condition is true. The for loop is commonly used with ranges like 1..5 or with iterators. You can break out of loops with break and skip iterations with continue.
fn main() {
let number = 7;
// if/else if/else
if number < 5 {
println!("less than 5");
} else if number < 10 {
println!("less than 10");
} else {
println!("10 or more");
}
// if as an expression
let condition = true;
let result = if condition { "yes" } else { "no" };
println!("Result: {}", result);
// loop - infinite loop
let mut count = 0;
loop {
count += 1;
if count == 3 {
break; // Exit the loop
}
println!("Count: {}", count);
}
// while loop
let mut num = 5;
while num > 0 {
println!("{}!", num);
num -= 1;
}
// for loop with range
for i in 1..=5 {
println!("i is {}", i);
}
}
Try it Yourself ->