Programming Languages
Rust
Subjective
Oct 04, 2025
How do closures work in Rust and what are the capture modes?
Detailed Explanation
Closures are anonymous functions:
• Can capture environment variables
• Three capture modes: by reference, by mutable reference, by value
• Implement Fn, FnMut, or FnOnce traits
• Type inference for parameters
• Move keyword for ownership transfer
Example:
let x = 4;
let equal_to_x = |z| z == x; // captures x by reference
let mut list = vec![1, 2, 3];
let mut borrows_mutably = || list.push(7); // captures by mutable reference
let moves = move || println!("x: {}", x); // moves x into closure
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts