Reputation: 15189
Consider the following code:
struct MyStruct {
not_copyable: NotCopyable
}
struct NotCopyable;
fn main() {
let foo = MyStruct { not_copyable: NotCopyable };
foo.not_copyable;
foo.not_copyable;
// just found out the simpler "foo; foo;" will create the same problem
}
This fails to compile with
src/main.rs:17:5: 17:21 error: use of moved value: `foo.not_copyable` [E0382]
src/main.rs:17 foo.not_copyable;
^~~~~~~~~~~~~~~~
src/main.rs:16:5: 16:21 note: `foo.not_copyable` moved here because it has type `NotCopyable`, which is non-copyable
src/main.rs:16 foo.not_copyable;
^~~~~~~~~~~~~~~~
error: aborting due to previous error
While I'm still not very versed in the ownership system, I think I get why you couldn't create two let
bindings to foo.not_copyable
. But in this case there is no binding. So who owns not_copyable
here; where did it move?
Upvotes: 3
Views: 71
Reputation: 59005
So who owns `not_copyable here; where did it move?
No one. The expression foo.not_copyable
has to pull the value out of the structure, because that value is the result of the expression. That you don't do anything with the value is beside the point; you asked for the value, it gave you the value.
It's possible the compiler might be able to optimise this out under certain circumstances, but without that, it's going to move the value like you asked it to.
And yes, foo;foo;
will do the same thing: just as NotCopyable
is not copyable, neither is MyString
.
Upvotes: 2