Rust Tutorial: Functions
Define and call functions, pass parameters, return values, and understand Rust's expression-based returns.
Functions
Functions are the primary unit of code organisation in Rust.
Key insight: the last expression in a function body is its return value — no `return` keyword needed.
What you'll learn in this Rust functions tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 18 minutes.
- Define and call a function — Use `fn` to define a function. Call it with its name and `()`.
- Parameters — Parameters use `name: type` syntax. Rust always requires type annotations on function parameters.
- Return values — Specify the return type with `->`. The last expression (without `;`) is returned.
- Explicit return — Use `return` for early exits from a function.
- Block expressions — A block `{}` is an expression. Its value is the last expression inside it.
- Multiple return values via tuple — Rust functions return one value, but that value can be a tuple.
- Functions as arguments — Functions can take other functions as parameters using `fn` types.
- Recursive functions — Functions can call themselves. Every recursive function needs a base case to stop.
Rust Functions concepts covered
- Functions