Question about using closures in multi threaded scenarios
⚓ Rust 📅 2026-02-28 👤 surdeus 👁️ 1Hi, im still learning Rust and Im really curious if I understand this part correctly.
use std::thread;
fn main() {
let v = vec![1,2,3];
let handle = thread::spawn(|| {
println!("Here's a vector: {:?}", v);
});
handle.join().unwrap();
}
The reason the compiler infers a borrow here is because the closure decides what to use based on what the body of the function does with the captured values. Since the code in the closure only uses the value in a println! statement a borrow is the logical choice. The closure is not aware that it will be run in a new thread. Only later while compiling will this problem be captured by the compiler.
Is my thought process here correct, am I on the right track?
2 posts - 2 participants
🏷️ Rust_feed