Closure capture modes
Quick answer
A closure is an anonymous function that can capture values from its surrounding scope. It is useful for short operations passed to methods or saved for later calls.
Borrow, mutate or move
Rust infers capture mode from how the closure uses external values. A read may borrow a value, a mutation may borrow it mutably, and consumption may move it. move requests capture by value; Copy values can be copied, while owned non-Copy values are moved. Calling a closure is not the same as creating it.
fn main() { let prefix = String::from("ID"); let format_id = |n: u32| format!("{prefix}-{n}"); println!("{}", format_id(5)); println!("{prefix}");}Expected stdout (not executed):
ID-5IDThe closure borrows prefix without consuming it.
fn main() { let name = String::from("Nila"); let greet = move || println!("Hello {name}"); greet(); greet();}Expected stdout (not executed):
Hello NilaHello NilaThe closure owns name but only reads it on each call.
Common mistake
Move capture does not necessarily mean the closure can only be called once.
Try it yourself
Write a closure that mutably captures a counter and increments it twice.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Closure capture modes — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A move closure owns a String but only reads it. Can it be called again?
Closure capture modes — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let prefix = String::from("ID"); let format_id = |n: u32| format!("{prefix}-{n}"); println!("{}", format_id(5)); println!("{prefix}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Closure capture modes — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let name = String::from("Nila"); let greet = move || println!("Hello {name}"); greet(); greet(); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.