Need to help to understand cannot < move out of borrowed content>

Hi,

I am beginner to Rust . I need help to understand (good if have examples) following errors from compiler for code

fn main() {
    let mut person = Person { cat: &Cat {} };
    person.test()
}


struct Person<'a> {
    cat: &'a Cat,
}

impl<'a> Person<'a> {
    fn test(self) {
        self.cat.meow();
    }
}

struct Cat {}

impl Cat {
    fn meow(self) {
        println!("meow")
    }
}
  1. Why we need to specify lifetime explicitly in Person class ?

  2. Need help what does following error means ?

    error[E0507]: cannot move out of borrowed content
      --> src/main.rs:16:9
       |
    16 |         self.cat.meow();
       |         ^^^^^^^^ cannot move out of borrowed content

Hi, welcome!

BTW, you almost never want to use references in structs. Borrowed data in structs is a special-case optimization that makes the whole struct restricted to a temporary usage. The whole mess with <'a> and lifetimes spreading like a disease are because you’re accidentally introducing a restriction for temporary use on everything your temporary struct touches.

Rust references are not what you think they are if you’re coming from another language that has objects passed by reference. Rust references are locks for restricting usage of data, not for holding onto things by reference. If you want to store something in a struct by reference, then use the Box pointer or Rc shared reference.

As for your question:

fn meow(self) 

takes ownership of self, meaning this has to be the only and the last place where Cat is used, and all previous places where it was have to be immediately destroyed/forgotten. This pattern is used for things like closing a file or disconnecting a network connection.

When you have &Cat it means you can look at it, but you can’t change it, and you definitely can’t force it to be the last and final use of it. You have it borrowed for temporary viewing, you don’t own it.

You probably want meow(&self) which doesn’t destroy self, only temporarily borrows it to use for duration of the method.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.