Why is the Closure Capture for an Array as Reference

I am just wondering about the difference in behavior in the following snippet:

fn main() {
    let v1 = String::new();
    std::thread::spawn(|| test1(v1));

    let v2 = [0; 16];
    std::thread::spawn(|| test2(v2));
}

fn test1(s: String) {}

fn test2(b: [u8; 16]) {}

Both are captured without move, and passed using a move to the function, but in case of the array Rust tells me:

closure may outlive the current function, but it borrows `v2`, which is owned by the current function

Why is there a difference? It feels to me like I am doing the same thing here :thinking:

Since the array is Copy, it can be captured by reference and then the reference can be copied out of, in order to satisfy calling test2() by-value. Unless necessary, closures capture by reference by default, hence whether a captured variable is copiable affects this decision.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.