Why on earth is this code not compiling? cannot move out of X which is behind a shared reference

Why on earth is this code not compiling?

use std::thread;
use std::thread::JoinHandle;

fn main() {
    let mut handles: Vec<JoinHandle<i32>> = Vec::new();

    let jh = thread::spawn(move || {
        1 + 1
    });

    handles.push(jh);

    for h in handles.iter() {
        h.join();
    }
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e9e38ae6197ebbf9c152bd01e569f658

JoinHandle consumes itself on join, so you just need to remove that .iter()

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=bfd66163f60f199a67254f4eb6d87562

(I would also unwrap to propagate panics)

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.