Functions & Closures in Rust

From the Rust cheat sheet ยท Functions & Closures ยท verified Jul 2026

Functions & Closures

Named functions, closures, and the Fn/FnMut/FnOnce traits.

rust
// Function with parameters and return type
fn add(a: i32, b: i32) -> i32 {
    a + b    // No semicolon = return value
}

// Closure โ€” anonymous function
let double = |x: i32| x * 2;
let sum = |a, b| a + b;
let result = double(5);  // 10

// Closure capturing variables
let name = String::from("Alice");
let greet = || println!("Hello, {name}");
๐Ÿ’ก No semicolon on the last expression makes it the return value โ€” this is idiomatic Rust
โšก Closures infer types from usage โ€” you rarely need type annotations on them
๐Ÿ“Œ Use move || to force a closure to take ownership โ€” required for spawning threads
๐ŸŸข Fn (immutable borrow) > FnMut (mutable borrow) > FnOnce (ownership) โ€” most closures are Fn
functionsclosuresfn-traits
Back to the full Rust cheat sheet