BeginnerLesson 4 of 16
Functions & Expressions – Rust
Parameters, return values, and the important difference between an expression and a statement.
You define functions with fn. Parameters and the return type must be specified (-> Type). The last expression without a semicolon is the return value; you only need return for early exits.
fn addiere(a: i32, b: i32) -> i32 {
a + b // no semicolon = return value
}
fn begruesse(name: &str) {
println!("Hello, {name}!"); // returns () (unit type)
}
fn main() {
println!("{}", addiere(2, 3)); // 5
begruesse("Ada");
}With tuples you return multiple values and take them apart with a pattern (destructuring):
fn min_max(z: &[i32]) -> (i32, i32) {
let mut min = z[0];
let mut max = z[0];
for &x in z {
if x < min { min = x; }
if x > max { max = x; }
}
(min, max)
}
fn main() {
let (lo, hi) = min_max(&[3, 9, 1, 7]);
println!("{lo} {hi}"); // 1 9
}Rust distinguishes statements (do something, produce no value, end with ;) from expressions (produce a value). Almost everything, including if, match, and blocks, is an expression:
fn main() {
let y = {
let a = 3;
a * a // block is an expression -> 9
};
println!("{y}");
}Warning
fn f() -> i32 { 5; } does not compile: the semicolon turns 5; into a statement, so the function returns () instead of i32. A common beginner mistake.TipRust has no default parameter values and no overloading. For optional arguments, people use
Option<T>, builder structs, or several functions.