struct Thing {
field: String,
}
fn copy_fn1(t: &Thing) -> String {
let tmp = *t; // compile failed
tmp.field.clone()
}
error[E0507]: cannot move out of `*t` which is behind a shared reference
--> src/main.rs:60:15
|
60 | let tmp = *t;
| ^^
| |
| move occurs because `*t` has type `Thing`, which does not implement the `Copy` trait
| help: consider borrowing here: `&*t`
根据提示改为
fn copy_fn1(t: &Thing) -> String {
let tmp = &*t; // compile success
tmp.field.clone()
}
以致我一直以为 copy是发生在 deref的时候,t 的时候,然后加上 &t后编译器可能做了什么操作将copy改为了引用,但实际上,这样也是没问题的。
fn copy_fn2(t: &Thing) -> String {
(*t).field.clone()
}
fn copy_fn3(t: &Thing) -> Thing {
*t // compile failed
}
实际上 *t 不会发生copy真正发生copy是在 = 或者 函数返回的地方