0

It seems to be fine to modify a vector on its own, but as soon as it is wrapped in a struct, it can not be mutated by a method on the struct.

I've created a very simplified version of my use case below, in two versions, one with just a vector, and one with a struct.

Why is it that this code is fine:

struct Task {
    foo: String,
}

fn main() {
    let mut list_of_tasks = Vec::new();

    loop {
        list_of_tasks.push(Task {
            foo: String::from("bar"),
        });
    }
}

But this is not:

struct Task {
    foo: String,
}

struct ListOfTasks(pub Vec<Task>);

impl ListOfTasks {
    fn push(mut self, task: Task) {
        self.0.push(task);
    }
}

fn main() {
    let list_of_tasks = ListOfTasks(Vec::new());

    loop {
        list_of_tasks.push(Task {
            foo: String::from("bar"),
        });
    }
}

The second example fails with:

error[E0382]: use of moved value: `list_of_tasks`
  --> src/main.rs:17:9
   |
14 |     let list_of_tasks = ListOfTasks(Vec::new());
   |         ------------- move occurs because `list_of_tasks` has type `ListOfTasks`, which does not implement the `Copy` trait
...
17 |         list_of_tasks.push(Task {
   |         ^^^^^^^^^^^^^ value moved here, in previous iteration of loop

I think I'm not understanding something about moving a struct that uses mut self, but can't find any obvious examples online of how to approach this.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
James Flight
  • 1,424
  • 1
  • 13
  • 21
  • See also [Error: “use of moved value”](https://stackoverflow.com/q/28277230/155423); [How to prevent a value from being moved?](https://stackoverflow.com/q/41664099/155423); [How can I solve “use of moved value” and “which does not implement the `Copy` trait”?](https://stackoverflow.com/q/49309847/155423); [Option Moved in Previous Loop Iteration](https://stackoverflow.com/q/54993331/155423) etc. – Shepmaster Oct 15 '19 at 19:22
  • You may also wish to re-read [What Is Ownership?](https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html) and [Defining Methods](https://doc.rust-lang.org/book/ch05-03-method-syntax.html#defining-methods) in *The Rust Programming Language*. – Shepmaster Oct 15 '19 at 19:23
  • 1
    You probably want `fn push(&mut self, task: Task)` – Shepmaster Oct 15 '19 at 19:23

0 Answers0