Closure Capture And Move Semantics

See how closures capture by borrow versus move, and when each mode is forced — the foundation for iterator chains that outlive their scope.

RustData Integrity

Code

rustsnippet
21 lines
fn main() {
    let factor = 3;
    // 借用捕获:闭包只读外部变量
    let scale = |x: i32| x * factor;
    println!("scaled: {}", scale(10));
    // 借用闭包存在时 factor 仍可读
    println!("factor still usable: {}", factor);

    let owned = String::from("payload");
    // move 闭包:取得所有权(send 到线程/超出作用域时必须)
    let consume = move || {
        println!("moved: {}", owned);
    };
    consume();
    // println!("{}", owned); // 已被移动:编译错误

    // 迭代器链的闭包同样捕获
    let nums = vec![1, 2, 3, 4];
    let evens: Vec<i32> = nums.iter().filter(|&&n| n % 2 == 0).map(|&n| n * factor).collect();
    println!("evens: {:?}", evens);
}

How the snippet works

Closure Capture And Move Semantics is built around the function main.

Using it

Running the file prints labeled results such as scaled:, factor still usable:, moved: — each operation’s effect is visible in the output.

Key statements

let evens: Vec<i32> = nums.iter().filter(|&&n| n % 2 == 0).map(|&n| n * factor).collect();
let consume = move || {
println!("moved: {}", owned);
};

Interactive Tools for This Topic

FAQ

What does Closure Capture And Move Semantics print when run?
The script runs standalone; its 4 labeled outputs include `scaled:`, `factor still usable:`, `moved:`.