Functions
A function is a named piece of code you can run again and again. You make one with fn.
Parameters
Inputs go in the round brackets. Every parameter needs a name and a type.
fn show(n: i32) { println!("n = {n}");}When you call show(4), you must pass exactly one i32.
Return types
-> T after the brackets says what the function gives back.
fn add(a: i32, b: i32) -> i32 { a + b}let x = add(2, 3); sets x to 5.
Expressions
In Rust, a block { } has a value: its last expression. That is why add needs no return.
let y = { let x = 3; x + 1}; // y is 4You can still use return to leave a function early: return x; gives back x right away.
The semicolon trap
A semicolon turns an expression into a statement. A statement has no value, so the block gives back () instead.
fn add(a: i32, b: i32) -> i32 { a + b; // error E0308}The function promised an i32 but its body now gives (). Remove the semicolon on the last line to fix it.
The unit type
() is called the unit type. It means "nothing useful to give back". A function with no -> returns (). So fn hello() is the same as fn hello() -> ().
Remember
- Every parameter needs a type.
-> Tsays what comes back.- The last expression, with no semicolon, is the return value.
- An extra semicolon on that last line is error E0308.
- No
->means the function returns().