Use of moved value: `self` problem

Hi, I am trying to write a simple class, and get a use of moved value: self error. Any suggestion? Thanks!

pub struct Robot {}

impl Robot {
    pub fn new() -> Self {
        Robot {}
    }
    pub fn advance(mut self) -> Self {
        self
    }
    pub fn instructions(mut self) -> Self {
        self.advance();
        self
    }
}

fn main() {}
error[E0382]: use of moved value: `self`
  --> src\main.rs:12:9
   |
10 |     pub fn instructions(mut self) -> Self {
   |                         -------- move occurs because `self` has type `Robot`, which does not implement the `Copy` trait
11 |         self.advance();
   |              --------- `self` moved due to this method call
12 |         self
   |         ^^^^ value used here after move
   |
note: this function takes ownership of the receiver `self`, which moves `self`
  --> src\main.rs:7:24
   |
7  |     pub fn advance(mut self) -> Self {
   |                        ^^^^

advance consumes it's self argument, since you're taking it by value. So when you do:

self.advance();

self is consumed, and then returned -- but you ignore the return value and it gets dropped. Perhaps instead you meant:

    pub fn instructions(mut self) -> Self {
        // self gets consumed by advance(), returned to here by advanced(), and then
        // in turn returned to our caller
        self.advance()
    }
1 Like

Thank you!