Moving value out of function by dereferencing a reference [duplicate]

家住魔仙堡 提交于 2020-01-25 06:52:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!