Functions, parameters and returned values
Functions, parameters and returned values
A school might apply the same bonus rule to many marks. A function gives that operation a name, accepts inputs through parameters and returns a result. A call supplies arguments. Separating the rule from printing lets you test the calculation independently.
What you’ll learn
- Write a typed function that returns a calculated mark.
- Explain how a trailing expression differs from a statement.
Functions, parameters and returned values in action
Arguments: 72 and 8
The arguments 72 and 8 bind to score and bonus.
Arguments: 72 and 8Calculate the sum
Their sum is 80, which the final expression returns.
Calculate the sumReturn: 80
Main stores the result and prints it.
Return: 80
Functions, parameters and returned values explained
Rust function parameters need declared types. -> i32 declares the returned type. A final expression without a semicolon supplies the result; a statement with a semicolon normally evaluates to unit, written (). You can also use return for an early exit.
Connect this idea with references and read-only borrowing.
Work through the Rust program
Save the complete source as main.rs in the Rust environment. No standard input is needed.
Rust 2024 · complete program
fn add_bonus(score: i32, bonus: i32) -> i32 {
score + bonus
}
fn main() {
let adjusted = add_bonus(72, 8);
println!("{adjusted}");
}Expected output
80Follow the execution
The arguments 72 and 8 bind to score and bonus. Their sum is 80, which the final expression returns. Main stores the result and prints it. Nothing inside add_bonus prints or changes an external mark.
Try the complete program in the Rust compiler. For tests, Cargo commands and local files, use the specified local environment.
Try a small variation
Your task: What happens if you add a semicolon after score + bonus without adding a return?
Rust 2024 · complete program
fn add_bonus(score: i32, bonus: i32) -> i32 {
score + bonus
}
fn main() {
let adjusted = add_bonus(72, 8);
println!("{adjusted}");
}Worked answer
The function body no longer supplies the required i32 result. Compilation fails because the declared return type and the body result disagree.
Mistakes and limits to recognize
Rust does not provide ordinary default or named arguments for functions. A returned value and a side effect are different outcomes. Introduce a helper when it names a useful operation, rather than creating tiny functions that hide straightforward logic.
Check your understanding
Take the idea into your next program
The function body no longer supplies the required i32 result. Compilation fails because the declared return type and the body result disagree. Rust does not provide ordinary default or named arguments for functions.
Further reading: the official Rust Book on functions, parameters and returned values.
Reaching the recap and completing the quizzes are separate milestones.