1. struct Thing {
    2. field: String,
    3. }
    4. fn copy_fn1(t: &Thing) -> String {
    5. let tmp = *t; // compile failed
    6. tmp.field.clone()
    7. }
    8. error[E0507]: cannot move out of `*t` which is behind a shared reference
    9. --> src/main.rs:60:15
    10. |
    11. 60 | let tmp = *t;
    12. | ^^
    13. | |
    14. | move occurs because `*t` has type `Thing`, which does not implement the `Copy` trait
    15. | help: consider borrowing here: `&*t`

    根据提示改为

    1. fn copy_fn1(t: &Thing) -> String {
    2. let tmp = &*t; // compile success
    3. tmp.field.clone()
    4. }

    以致我一直以为 copy是发生在 deref的时候,t 的时候,然后加上 &t后编译器可能做了什么操作将copy改为了引用,但实际上,这样也是没问题的。

    1. fn copy_fn2(t: &Thing) -> String {
    2. (*t).field.clone()
    3. }
    4. fn copy_fn3(t: &Thing) -> Thing {
    5. *t // compile failed
    6. }

    实际上 *t 不会发生copy真正发生copy是在 = 或者 函数返回的地方