Why is "capture by reference" equivalent to "capture a reference by value" in Rust?

Viewed 252

Excerpt from Huon Wilson's Finding Closure in Rust:

Capturing entirely by value is also strictly more general than capturing by reference: the reference types are first-class in Rust, so "capture by reference" is the same as "capture a reference by value". Thus, unlike C++, there’s little fundamental distinction between capture by reference and by value, and the analysis Rust does is not actually necessary: it just makes programmers’ lives easier.

I struggle to wrap my head around this. If you capture a reference "by value", don't you capture the data that is stored on the heap? Or does it refer to the pointer value of the reference, which is found on the stack?

2 Answers

I think the article means to say that the effect is almost equivalent. Immutable references implement Copy trait because of which when you capture a reference by value, it is copied. So basically you just created one more shared reference to the same data.

fn as_ref(_x: &String) {}

fn as_mut(_x: &mut String) {}

fn main() {
    let mut x = String::from("hello world");
    let y = &x;

    let _ = move || {
        as_ref(y); // here you moved y but it
                   // basically created a copy
    };

    let z = y; // can be used later

    // The same cannot be done by mutable
    // refs because they don't
    // implement Copy trait
    
    let y = &mut x;

    let _ = move || {
        as_mut(y); // here you moved y and
                   // it cannot be used outside
    };

    // ERROR! Cannot be used again
    //let z = y;
}

Playground

Or does it refer to the pointer value of the reference, which is found on the stack?

Yes, ish.

In Rust, references are reified, they're an actual thing you manipulate. So when you capture a reference by value, you're capturing the reference itself (the pointer, which is what a Rust reference really is), not the referee (the pointee).

Capturing by reference basically just implicitly creates a reference and captures it by value.

Related