4

Example:

struct Something(Thing);

impl Something {
    fn run(&self) -> &Thing {
        // This works (as expected)
        // let thing = &self.0;

        // This doesn't work. (temporary value)
        //   let thing = &self.0.clone();

        // Then why does this work? (isn't this a temporary value?)
        let thing = &Thing {};

        thing
    }
}

#[derive(Clone)]
struct Thing {}

I don't understand why am I allowed to create a Thing{} and return a reference to it, but I am unable to clone and return the existing one in the struct field.

Playground

gauge
  • 1,073
  • 2
  • 11
  • 17
  • 3
    This is the same reason why you can return a string literal from a function. When creating a value and putting it behind a reference immediately, Rust gives it a `'static` lifetime. This means that the value can live for the entire duration of the program. – Aloso Apr 18 '20 at 02:48

0 Answers0