Topic
Functions
A function is a named block of code that takes inputs, does something with them, and can hand a value back. In Rust, every function that returns a value must declare its return type, and the last line of the function body is what gets returned.
Quick Reference
| Concept | What it means |
|---|---|
| fn name() | Declare a function named name |
| fn name(x: i32) | Function with one parameter: x of type i32 |
| fn name(x: i32, y: i32) | Two parameters, each needs its own type |
| -> i32 | The function returns an i32 to whoever called it |
| Caller | The code that calls a function and receives what it returns |
| Term | What it means | When you use it |
|---|---|---|
| fn name() | Declare a function named name | Any time you want a named, reusable block of code |
| fn name(x: i32) | Function with one parameter: x of type i32 | When a function needs an input value to work with |
| fn name(x: i32, y: i32) | Two parameters, each needs its own type annotation | When the function takes multiple inputs |
| -> i32 | The function returns an i32 to whoever called it | Any function that hands a value back to the caller |
| Caller | The code that calls a function and receives what it returns | Understanding where a function's return value goes |