Guide

Control flow

Control flow decides which code runs, and how many times.

if is an expression

if runs code only when a condition is true. The condition must be a bool; a number like 1 is not allowed.

let n = 7;if n > 5 {    println!("big");} else {    println!("small");}

if also gives back a value, so you can use it on the right of let. Both branches must have the same type.

let kind = if n % 2 == 0 { "even" } else { "odd" };

Add more checks with else if. Rust tries each condition in order and runs the first branch that is true.

loop

loop repeats forever until it reaches break. break can carry a value out of the loop.

let mut n = 0;let r = loop {    n += 1;   // short for n = n + 1    if n == 3 { break n * 10; }};  // r is 30

-= and *= work like +=: n -= 1 is n = n - 1.

while

while checks its condition before each pass. It stops as soon as the condition is false.

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

for and ranges

for walks over a range of numbers.

  • 0..3 gives 0, 1, 2. The end is left out.
  • 0..=3 gives 0, 1, 2, 3. The end is included.
for i in 1..=3 {    println!("{i}");}

Loop labels

continue skips the rest of this pass and starts the next one. break and continue act on the innermost loop. To reach an outer loop, give it a label that starts with '.

'outer: for i in 0..3 {    for j in 0..3 {        if j == 1 { continue 'outer; }        println!("{i}{j}");    }}

Remember

  • An if condition must be a bool.
  • if and loop can give back values.
  • a..b leaves out b; a..=b includes it.
  • Use a label like 'outer to break out of an outer loop.