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 pay5, everyone else pays12. Use guard clauses withreturn.safe_divide(a: i32, b: i32) -> i32: return0whenbis0(guard first), otherwisea / b.first_multiple_of_seven(limit: u32) -> u32: loop over1..=limitand return the first number divisible by 7. If there is none, return0.