I would like to understand why the outer stack variable data in the below example does not require the move keyword to be used with the closure.
The example is taken from the Curl crate, and the documentation states the the lifetime of the write_function is taken from the transfer variable, and because of this the closure can access the stack variable data without moving it.
Here is an quote from the documentation:
Note that the lifetime bound on this function is 'static, but that is often too restrictive. To use stack data consider calling the transfer method and then using write_function to configure a callback that can reference stack-local data.
See: https://docs.rs/curl/0.4.6/curl/easy/struct.Easy.html#method.write_function
use curl::easy::Easy;
let mut data = Vec::new();
let mut handle = Easy::new();
handle.url("https://www.rust-lang.org/").unwrap();
{
let mut transfer = handle.transfer();
transfer.write_function(|new_data| {
data.extend_from_slice(new_data);
Ok(new_data.len())
}).unwrap();
transfer.perform().unwrap();
}
println!("{:?}", data);
Why does this work?
Alternatively, if I try to use the write_function from the handle directly, then I get a borrowing error that data has been moved.
Here is an example that does not work, and I understand why it doesn't work. I'm confused why the above works instead.
use curl::easy::Easy;
let mut data = Vec::new();
let mut handle = Easy::new();
handle.url("https://www.rust-lang.org/").unwrap();
handle.write_function(move |new_data| {
data.extend_from_slice(new_data);
Ok(new_data.len())
}).unwrap();
handle.perform().unwrap();
println!("{:?}", data);
// ^^^^ error because it was moved