ClosuresIntermediate
1Question 1 of 1
rustHow do Closures work in Rust (Fn, FnMut, FnOnce)?
Explanation & Concept
Rust closures capture variables from their enclosing environment using three traits:
• `FnOnce`: Consumes captured variables (can be called once). • `FnMut`: Mutably borrows captured variables. • `Fn`: Immutably borrows captured variables.
Use the `move` keyword to force transferring ownership of captured variables into the closure.
Code Example
rust
fn main() {
let factor = 3;
// Implements Fn: borrows factor immutably
let multiply = |x: i32| x * factor;
println!("Result: {}", multiply(10)); // 30
let mut count = 0;
// Implements FnMut: mutates count
let mut increment = || count += 1;
increment();
println!("Count: {}", count); // 1
}How It Works & Key Takeaways
The Rust compiler infers closure trait implementations automatically based on how captured variables are manipulated.
Mock Test · 1 Questions · Optional
Ready for Modules & Crates?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions