Function Declaration
In Rust, function parameters must have type annotations, and the return type is specified with ->:
fn add(x: i32, y: i32) -> i32 {
x + y // no semicolon = return value (expression)
}
fn main() {
let result = add(5, 10);
println!("5 + 10 = {}", result); // 5 + 10 = 15
}
Expressions vs Statements
// Statement: performs action, no return value
let x = 5;
// Expression: evaluates to a value
let y = {
let a = 3;
a * a + 1 // no semicolon — this is the block's value
};
println!("{}", y); // 10
// The last expression in a function is the return value
fn square(n: i32) -> i32 {
n * n // equivalent to: return n * n;
}
Multiple return values with tuples
fn min_max(v: &[i32]) -> (i32, i32) {
let mut min = v[0];
let mut max = v[0];
for &x in &v[1..] {
if x < min { min = x; }
if x > max { max = x; }
}
(min, max)
}
let nums = vec![3, 1, 4, 1, 5, 9, 2, 6];
let (min, max) = min_max(&nums);
println!("min={}, max={}", min, max);
Closures
// Closure syntax: |params| expression
let double = |x| x * 2;
println!("{}", double(5)); // 10
// Closures can capture their environment
let offset = 10;
let add_offset = |x| x + offset;
println!("{}", add_offset(5)); // 15
// Used with iterators
let nums = vec![1, 2, 3, 4, 5];
let doubled: Vec = nums.iter().map(|&x| x * 2).collect();
println!("{:?}", doubled); // [2, 4, 6, 8, 10]