1

Given this code:

struct SimpleFoo {}

fn create_simplefoo() -> SimpleFoo {
    let foo: &SimpleFoo = &SimpleFoo {};
    *foo
}

pub fn main() {
    let foo = create_simplefoo();
}

I get

error[E0507]: cannot move out of `*foo` which is behind a shared reference
 --> src/main.rs:5:5
  |
5 |     *foo
  |     ^^^^ move occurs because `*foo` has type `SimpleFoo`, which does not implement the `Copy` trait

It seems that foo has the SimpleFoo instance borrowed. That makes sense since it's a reference, not a value - but who's the owner then? I thought that any value in Rust has always an owner. Was that incorrect assumption?

I think this kind of initialization by reference construct (let foo: &SimpleFoo = &SimpleFoo {};) contains some Rust concept I am not aware of. What am I missing?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Patrik Stas
  • 1,883
  • 17
  • 24
  • 2
    Does this answer your question? [Why can I return a reference to a local literal but not a variable?](https://stackoverflow.com/questions/50345139/why-can-i-return-a-reference-to-a-local-literal-but-not-a-variable) – justinas Dec 16 '19 at 14:59
  • 2
    ^ This seems to answer your question about the owner: in your case SimpleFoo is promoted to a static. It is also legal to [mutably borrow a temporary](https://stackoverflow.com/questions/47662253/why-is-it-legal-to-borrow-a-temporary) but in that case it would create a fresh SimpleFoo (otherwise, you could take several mutable references to the same one). – justinas Dec 16 '19 at 14:59
  • 2
    *who's the owner* — as shown in the duplicate, the owner is variable that you can't see. Since you can't see it, you can't move out of it. – Shepmaster Dec 16 '19 at 15:01

0 Answers0