Functions
| Define fn | |
| Parameters | |
| Return without semicolon | |
| Diverging fns |
Define fn
A function groups steps under one name with fn. Call it by name with round brackets and matching arguments:
fn greet() {
println!("hi");
}
Parameters
Parameters list each input with a name and a type. Calls must pass matching values in the same order:
fn add(x: i32, y: i32) -> i32 {
x + y
}
Return without semicolon
The last expression without a semicolon becomes the return value. Use return only for early exits from the middle:
fn double(x: i32) -> i32 {
x * 2
}
Diverging fns
A diverging function never returns and uses the never type. It marks panics and endless loops in the signature:
fn stop(msg: &str) -> ! {
panic!("{}", msg);
}
Next: Structs
Article author: Arthur Isaev