Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
use std::thread;
fn main() {
let v = vec![1, 2, 3];
let h = thread::spawn(|| println!("{v:?}"));
h.join().unwrap();
}It does not compile
- Expecting
[1, 2, 3]becausejoincomes right afterspawn: the compiler checks the signature ofspawn, not what happens later, and the closure must own what it uses. - Expecting the closure to take
vby itself because a thread needs it: a closure borrows what it only reads, and onlymovemakes it take ownership.
- What changes if you write
move ||, and canmainstill printvafterjoin? - How would you give the thread its own copy while
mainkeeps the original vector?