1

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
nikoss
  • 3,254
  • 2
  • 26
  • 40

1 Answers1

4

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    I start to hate their way of teaching things . They could at least tell before hand that this isnt a working example – nikoss Nov 11 '18 at 23:08
  • 2
    @nikoss If you are aren't happy with the current situation (which I can understand) you're always welcome to open an issue/pull request [at github](https://github.com/rust-lang/book) and improve the situation. This is an important step, because somebody who already knows rust, does not stumple upon these errors, because they know what's up. But newcommers like you are having a hard time, and I think this should be improved. Feel free to be part of the rust community <3 – hellow Nov 12 '18 at 07:08