问题
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?
来源:https://stackoverflow.com/questions/59358981/moving-value-out-of-function-by-dereferencing-a-reference