Cannot move, I don't konw why and how to fix it

Hello everyone, I am a new rust learner, i think i lost some points so that it leads the issue.But i am not able fix it :face_exhaling:.

pub struct  Job{
    detail: Task,

type Task = Box<dyn FnOnce() + Send + 'static>;

impl Job{
    pub fn new (task: Task) ->Self {
            detail: Box::new(task),

    pub fn job(&self, i:i8) -> Task {

the function jon() alerts "cannot move", why and how to fix it?

You are not allowed to move out of a reference, for obvious reasons: if you move (and thus invalidate) the referent, then the reference would be dangling.

It appears that you aren't yet familiar with Rust's ownership and borrowing system. Please read The Book from the beginning to get acquainted with the fundamentals.

1 Like

If you want to give a temporary access to Task, then return &Task (edit: if Task was a struct or Fn).

If you want to destroy the Job object and leave only Task behind, then make the method take self instead of &self.

You can also wrap Task in Option<Task> and use .take() to return it, leaving None behind.


That is not going to work for a dyn FnOnce, because it won't be callable given only a reference.

You could use fn() for Task.

You could use Box<dyn Fn() + ...> and borrow a &(dyn Fn() + ...).

Independently of your error, in new:

type Task = Box<dyn FnOnce() + Send + 'static>;

impl Job {
    pub fn new(task: Task) -> Self {
        Job {
            detail: Box::new(task),

You already have a Box<...> so you shouldn't box it again. You're just creating needless indirection.

    pub fn new(detail: Task) -> Self {
        Job { detail }

By the way, if you run cargo check (or cargo build etc), you'll get more informative errors than your IDE provides:

  --> src/
16 |         self.detail
   |         ^^^^^^^^^^^ move occurs because `self.detail` has type `Box<dyn FnOnce() + Send>`, which does not implement the `Copy` trait

For more information about this error, try `rustc --explain E0507`.

And incidentally, full errors in textual form like this are preferred over screenshots on this forum.


yes, yes, it is my mistake, i don't find the error until you tell me. Thanks very much.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.