As the planner grows, the same calculations appear in several places: total minutes for a topic, minutes left until a goal. Copying a formula is risky, because a fix in one copy does not reach the others. A function gives a piece of work a name, so you write it once and call it wherever you need it. You have been writing one function all along: main.
A function definition lists its parameters: names, each with a type, that stand for the inputs. A call supplies arguments: the actual values for one use. -> i32 after the parameter list declares the type of the value the function returns. Rust insists on types in the definition, even though it infers them inside function bodies. The signature is a contract: anyone calling the function can read exactly what goes in and what comes out without reading the body, and the compiler checks every call against it.
Predict and run
The last expression of a block becomes the block's value when it has no trailing semicolon. Here, the multiplication is the return value. main calls the function twice with different arguments. Predict both lines. Which argument changes between calls?
fn total_minutes(sessions: i32, per_session: i32) -> i32 {
sessions * per_session
}
fn main() {
println!("{}", total_minutes(3, 25));
println!("{}", total_minutes(4, 25));
}Check your prediction
75
100Arguments are matched to parameters by position: in the first call, sessions is 3 and per_session is 25. Only the first argument changes. Now add a semicolon after the multiplication and run:
fn total_minutes(sessions: i32, per_session: i32) -> i32 {
sessions * per_session;
}You get error[E0308]: mismatched types with expected i32, found (), and the help remove this semicolon to return this value. The semicolon turns the expression into a statement that produces nothing, written (), so the function no longer returns the i32 it promised. Restore the tail expression. The compiler also checks the number of arguments: total_minutes(3) fails with error[E0061]: this function takes 2 arguments but 1 argument was supplied.
Leave early with return
Sometimes the answer is known before the end of the function. return hands back a value immediately and skips the rest of the body. It is handy for a special case at the top, sometimes called a guard.
fn break_minutes(minutes: i32) -> i32 {
if minutes < 25 {
return 0;
}
minutes / 5
}
fn main() {
println!("{}", break_minutes(20));
println!("{}", break_minutes(25));
println!("{}", break_minutes(50));
}0
5
10A 20-minute session earns no break, so the function returns 0 and never reaches the division. Longer sessions skip the if and fall through to the tail expression. Both styles are common; the tail expression is preferred for the normal result, and return for the early exits.
Functions that only do something
Not every function calculates a value. A function without -> returns nothing, and its job is its effect, such as printing. Calling it inside a loop keeps the loop short and gives the repeated work a clear name.
fn report(day: i32, minutes: i32) {
if minutes == 0 {
println!("Day {day}: rest");
} else {
println!("Day {day}: {minutes} min");
}
}
fn main() {
let durations = [30, 0, 45];
let mut day = 1;
for minutes in durations {
report(day, minutes);
day += 1;
}
}Day 1: 30 min
Day 2: rest
Day 3: 45 minreport receives a copy of each number, so it cannot change day or the array in main. Its parameters are its own bindings, which disappear when the call ends.
Name functions after their answer
A good function name tells the caller what comes back, such as total_minutes or break_minutes. If you struggle to name it, the function is probably doing two jobs.
Practice
Your turn
Complete remaining(goal, done). Return how many minutes are still needed to reach the goal, and zero once the goal is reached or passed. The starter calls it below, at and above the goal, and should print 25, 0 and 0.
fn remaining(goal: i32, done: i32) -> i32 {
0
}
fn main() {
println!("{}", remaining(60, 35));
println!("{}", remaining(60, 60));
println!("{}", remaining(60, 75));
}Hint 1: the idea
An if expression can be the function's tail expression, as long as both branches produce an i32.
Hint 2: a first step
Use if done < goal to pick the subtraction path, and give the else branch the value 0.
Worked solution
fn remaining(goal: i32, done: i32) -> i32 {
if done < goal {
goal - done
} else {
0
}
}
fn main() {
println!("{}", remaining(60, 35));
println!("{}", remaining(60, 60));
println!("{}", remaining(60, 75));
}25
0
0Without the condition, the third call would return -15, which makes no sense as minutes left. The middle call is the boundary: at exactly 60, done < goal is false and the result is 0. The checkpoint combines a function like this with a loop.
Completion is saved in this browser only. It does not measure mastery.