0
fn main() { 
  struct Person {
      name: String
  }
  
  impl Person {
      fn get_name(&self) -> String {
          self.name
      }
  }
  
  let me = Person {
    name: String::from("Manuel")  
  };
  
  println!("{}", me.get_name());
}

Given this code the compiler returns the error

self.name | ^^^^^^^^^ move occurs because self.name has type String, which does not implement the Copy trait

So i fixed it with

 fn get_name(&self) -> &String {
     &self.name
 }

But i don't get why? Given that I already defined the argument as &self, why I have to specify the & operator also to the return type and value? In my head, the &self already means "whatever is passed as argument, it is already a borrow of the pointer"

I'm a bit confused

mpalma
  • 88
  • 7
  • 2
    `self` is borrowed, but the return value is not necessarily. – Chayim Friedman Jan 10 '22 at 12:42
  • 1
    In rust almos everything is splicit. String do not implement copy, but you actually want a String to be returned. So the compiler is tring to move the value out of the struct. – Netwave Jan 10 '22 at 12:42
  • How would you define a method that should return an owned value then, assuming what you proposed would work out of the box? You might even want to return a value that isn't even in the struct, so it wouldn't make sense to default to borrowing. – peterulb Jan 10 '22 at 13:02
  • Thanks for your replies. I just don't get why if the argument is a borrow, returning without & would be the original value moved – mpalma Jan 10 '22 at 13:27
  • What about `fn f(&self) -> i32 { 0 }`? Is this valid? It does not return a borrow, or even something from `self`! – Chayim Friedman Jan 10 '22 at 13:29
  • 1
    @mpalma Because you only access the struct via a reference. Once you obtain the memory location, what is stored there might or might not be a reference. `self.name` simply means follow the self reference and then access what is stored for name. In your case the 24 bytes making up the string. If you want a reference to this specific value, you'll have to specify just that – peterulb Jan 10 '22 at 16:06

0 Answers0