Code Example Template
Deep-Dive System Documentation
Closures: Context Capturing callbacks
A closure is an anonymous function that can capture variables from its enclosing scope. They are written using pipe boundaries || instead of parentheses.
let active_key = 0x41;
// Closure captures 'active_key' from environment automatically!
let is_active_key = |code| code == active_key;
assert!(is_active_key(0x41));
Trait Category Implementations
The compiler packages closures into anonymous structs implementing one of three built-in traits, depending on how variables are captured:
Fn: Captures variables by reference (&T). Can be invoked multiple times.FnMut: Captures variables by mutable reference (&mut T). Can mutate variables, can be called multiple times.FnOnce: Consumes and takes ownership of captured variables. Can only be invoked once.
// FnOnce example capturing by moving ownership
let profile_name = String::from("Vercel");
let run_process = move || {
let name = profile_name; // owned, moved
spawn_worker(name);
};
Quick Reference Guide
let add_one = |x| x + 1;
let res = add_one(5);