FerrousPath

Level 1 · Foundations· Lesson 3 of 10 · 20 min

Functions and control flow

Expressions versus statements, functions, if, loops, and why almost everything in Rust produces a value.

Functions

fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn main() {
    println!("{}", add(2, 3));
}

Parameter types are always written out. The return type follows ->. And notice there is no return and no semicolon after a + b — that is the heart of this lesson.

Expressions and statements

Rust is an expression-oriented language. An expression evaluates to a value. A statement performs an action and evaluates to nothing useful.

  • a + b is an expression.
  • let x = 5; is a statement.
  • A block { ... } is an expression: its value is the value of its last expression, written without a semicolon.
  • Adding a semicolon to an expression turns it into a statement and discards its value.
fn main() {
    let y = {
        let x = 3;
        x * x + 1 // no semicolon: this is the block's value
    };
    println!("{y}");
}

A function body is a block, so its last expression is the return value. return exists for leaving early:

fn describe(n: i32) -> &'static str {
    if n < 0 {
        return "negative";
    }
    if n == 0 { "zero" } else { "positive" }
}

fn main() {
    println!("{} {} {}", describe(-5), describe(0), describe(9));
}

if is an expression

There is no ternary operator because if already is one. The condition must be a bool — Rust has no “truthy” values.

fn main() {
    let temperature = 31;
    let advice = if temperature > 28 { "stay inside" } else { "go out" };
    println!("{advice}");
}

Both branches must have the same type. if x { 1 } else { "one" } is a compile error.

Loops

Rust has three loops.

fn main() {
    // `loop` runs until you break. It can return a value.
    let mut n = 1u32;
    let first_power_over_1000 = loop {
        n *= 2;
        if n > 1000 {
            break n;
        }
    };
    println!("{first_power_over_1000}");

    // `while` runs while a condition holds.
    let mut countdown = 3;
    while countdown > 0 {
        println!("{countdown}…");
        countdown -= 1;
    }

    // `for` iterates over anything iterable. This is the loop you will use most.
    for i in 1..=3 {
        println!("lap {i}");
    }
    for (index, word) in ["alpha", "beta", "gamma"].iter().enumerate() {
        println!("{index}: {word}");
    }
}

Prefer for over indexing with a counter. It cannot go out of bounds, and it is usually faster because the bounds checks disappear.

Loop labels

To break out of an outer loop from an inner one, label it:

fn main() {
    'rows: for row in 0..5 {
        for col in 0..5 {
            if row * col == 6 {
                println!("found at ({row}, {col})");
                break 'rows;
            }
        }
    }
}

A first look at match

match compares a value against patterns and must cover every possibility. You will meet its full power in the lesson on enums.

fn fizzbuzz(n: u32) -> String {
    match (n % 3, n % 5) {
        (0, 0) => String::from("FizzBuzz"),
        (0, _) => String::from("Fizz"),
        (_, 0) => String::from("Buzz"),
        _ => n.to_string(),
    }
}

fn main() {
    for n in 1..=15 {
        println!("{}", fizzbuzz(n));
    }
}

The _ pattern matches anything. Delete the last arm and read the error: the compiler tells you exactly which cases you forgot.

Exercises

  1. Write fn is_prime(n: u32) -> bool and print all primes below 50.
  2. Write fn fib(n: u32) -> u64 iteratively, with a for loop and two mutable variables.
  3. Write fn collatz_steps(mut n: u64) -> u32 that counts steps until n reaches 1 (halve if even, 3n + 1 if odd).
Solution to 1
fn is_prime(n: u32) -> bool {
    if n < 2 {
        return false;
    }
    let mut d = 2;
    while d * d <= n {
        if n % d == 0 {
            return false;
        }
        d += 1;
    }
    true
}

fn main() {
    for n in 0..50 {
        if is_prime(n) {
            print!("{n} ");
        }
    }
    println!();
}

Check your understanding

Pick an answer to see the explanation.

  1. 1.What does this function return? fn f() -> i32 { 5; }

  2. 2.Which loop construct can produce a value with break value?

  3. 3.What does 1..=5 produce?

Key terms in this lesson

Finished the lesson and the exercises?