Give each idea a boundary.
Write functions with explicit inputs and useful return values.
01 Understand the contract
Function signatures describe the contract between caller and callee. Parameter types and non-unit return types are written explicitly. Most Rust blocks are expressions: their final expression becomes the value if it has no trailing semicolon. Statements perform actions; a semicolon can turn a value-producing expression into a statement. Keep a function focused enough to test with ordinary values. Prefer returning a result to printing inside low-level logic, so callers can decide how to display it.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn total(price: u32, quantity: u32) -> u32 {
price * quantity
}
fn main() {
let invoice = {
let shipping = 5;
total(12, 3) + shipping
};
println!("total={invoice}");
}total=41
- 1
total returns its final multiplication expression.
- 2
The inner block computes a value using a local shipping binding.
- 3
The example uses small values; production arithmetic still needs bounds or checked operations.
cargo run -p lesson_functions03 Mind the boundary
04 Your next build
Write a function that computes the perimeter of a rectangle and test two sizes.
Reveal one possible solution +
fn perimeter(width: u32, height: u32) -> u32 {
2 * (width + height)
}
fn main() {
assert_eq!(perimeter(3, 5), 16);
assert_eq!(perimeter(1, 1), 4);
}05 Check your reasoning
What returns a block’s final value?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.