Defines a function.
Syntax
fn name(p: type) -> returnType { ... }Description
Parameter types are written with :, return types with ->. The last expression (without a semicolon) is returned automatically — no return needed.
Example
fn square(x: i32) -> i32 {
x * x
}
fn main() {
println!("{}", square(5));
}Expected output
25
When to use?
Preventing code repetition.
Common mistakes
- ⚠️ Do NOT put a ; at the end of the final returned expression: x * x (returns), x * x; (does not return).