Rust Fundamentals · 15 XP

Returning early

Usually the last expression is a function's result, but sometimes you want to leave sooner. The return keyword exits the function immediately with a value. It ends with a semicolon and may appear anywhere, even inside a loop.

A popular pattern is the guard clause: handle the special cases first and return, so the main logic stays flat and readable.

fn describe(age: u32) -> &'static str {
    if age < 13 {
        return "child";
    }
    if age < 20 {
        return "teen";
    }
    "adult"
}

Inside a loop, return lets you stop as soon as you have found what you want:

fn first_big(limit: u32) -> u32 {
    for n in 1..=limit {
        if n * n > 50 {
            return n;
        }
    }
    0
}

Your task

  • ticket_price(age: u32) -> u32: children under 3 travel free (0), people aged 65 or over pay 5, everyone else pays 12. Use guard clauses with return.
  • safe_divide(a: i32, b: i32) -> i32: return 0 when b is 0 (guard first), otherwise a / b.
  • first_multiple_of_seven(limit: u32) -> u32: loop over 1..=limit and return the first number divisible by 7. If there is none, return 0.

Next lesson →

Sign in to run your code. It's free.