RRust By Example
intermediateOwnership

Closure Ownership

How closures capture values: by reference, mutable reference, or by value.

Closure Ownership

How closures capture values: by reference, mutable reference, or by value.

Difficulty

Intermediate

Code

rust
fn main() {
    // borrow immutably
    let name = String::from("Alice");
    let greet = || println!("Hello, {}!", name);
    greet();
    println!("name still valid: {}", name);

    // borrow mutably
    let mut nums = vec![1, 2, 3];
    let mut push = || nums.push(4);
    push();
    println!("{:?}", nums);

    // move ownership
    let data = String::from("moved");
    let own = move || println!("{}", data);
    own();
    // println!("{}", data); // error: value used after move
}

Explanation

Closures capture by reference, mutable reference, or value (move).

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the ownership category to build a complete understanding of this topic.

More Ownership Examples