Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who owns a value without a let binding?

Tags:

rust

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?

like image 268
musiKk Avatar asked Dec 14 '25 08:12

musiKk


1 Answers

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.

like image 69
DK. Avatar answered Dec 16 '25 21:12

DK.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!