nikoss
nikoss

Reputation: 3698

Why does the multithreaded web server example from the Rust book not compile?

This is a code sample from the book:

use std::{
    sync::{mpsc, Arc, Mutex},
    thread,
};

struct Worker {
    id: usize,
    thread: thread::JoinHandle<()>,
}

impl Worker {
    fn new(
        id: usize,
        receiver: Arc<Mutex<mpsc::Receiver<Box<dyn FnOnce() + Send + 'static>>>>,
    ) -> Worker {
        let thread = thread::spawn(move || loop {
            let job = receiver.lock().unwrap().recv().unwrap();

            println!("Worker {} got a job; executing.", id);

            (*job)();
        });

        Worker { id, thread }
    }
}

playground

It doesn't compile:

error[E0161]: cannot move a value of type dyn std::ops::FnOnce() + std::marker::Send: the size of dyn std::ops::FnOnce() + std::marker::Send cannot be statically determined
  --> src/lib.rs:21:13
   |
21 |             (*job)();
   |             ^^^^^^

Is this a bug in the book or am I missing something?

Upvotes: 1

Views: 566

Answers (1)

Shepmaster
Shepmaster

Reputation: 431479

It seems that you are referring to the section of the book that is immediately followed by the text:

Theoretically, this code should compile. Unfortunately, the Rust compiler isn’t perfect yet, and we get this error:

error[E0161]: cannot move a value of type std::ops::FnOnce() +
std::marker::Send: the size of std::ops::FnOnce() + std::marker::Send cannot be
statically determined
  --> src/lib.rs:63:17
   |
63 |                 (*job)();
   |                 ^^^^^^

Thus no, it's not a bug in the book; they deliberately included that to show a problem. Please continue reading the chapter to see how they suggest addressing it.

See also:

Upvotes: 4

Related Questions