Control Flow
Control flow
Control flow constructs allow you to run code conditionally or repeatedly, directing the "flow" of your program's execution. Rust provides several familiar ways to do this.
If Else
if
, else
, and else if
allow you to execute different blocks of code based on whether a boolean condition is true or false:
fn main() { let number = 3; // Note that `if` is an expression, meaning it evaluates to a value. let result: u8 = if number < 5 { println!("Condition was true"); // The value of the `if` expression is the value of the last expression // in the block. 5 } else { println!("Condition was false"); 6 }; // Semicolon here, because `let` is a statement. println!("{}", result); } // All branches of an `if/else` expression must evaluate to the same type, // if you intend to assign the result to a variable.
Loop
loop
creates an infinite loop that runs until explicitly stopped, usually with the break
keyword.
Like if
, loop
is also an expression, and break
can return a value from the loop.
/// Demonstrates the use of a `loop` with a `break` statement to return a value. fn main() { // Initialize a mutable counter. let mut counter = 0; // The `loop` keyword creates an infinite loop. // Note that it is an expression. let result = loop { counter += 1; if counter == 10 { break counter * 2; // The value passed to `break` is returned by the loop. // `continue` and loop labels also exist. // See https://doc.rust-lang.org/book/ch03-05-control-flow.html } }; println!("{}", result); }
You can also use continue
to skip the rest of the current iteration and start the next one. Loops can also have labels ('label: loop { ... break 'label; }
) for breaking or continuing to outer loops from within nested loops.
While
while
executes a block of code repeatedly as long as a boolean condition remains true.
The condition is checked before each iteration.
/// This is an example of a `while` loop. fn main() { // Initialize a mutable variable. let mut number = 5; // The loop continues as long as the condition is true. while number != 0 { println!("{number}!"); // Decrement the number. number -= 1; } // Prints: 5! 4! 3! 2! 1! }
For
for
is used to iterate over the items produced by an iterator. Many types, like arrays, ranges, vectors, and strings (via methods like .lines()
or .chars()
), can produce iterators.
fn main() { // Iterate over an array. let a = [10, 20, 30, 40, 50]; for element in a { println!("the value is: {element}"); } // Range - generates all numbers in sequence, // starting from one number and ending before another number. for number in (1..4).rev() { // Use `rev` for reverse enumeration. println!("{number}!"); } }
Related Topics
- Match.
- Rust Patterns.