let z = *y;
This line only knows y
, and y
is a &String
. &String
doesn't carry any information where it comes from, it only carries the information that it is a reference to a String
. It doesn't know or care about the fact that x
contains the actual content, nor does it have any control over x
, apart of the fact that the borrow checker makes sure that x
stays in scope and immutable.
So *y
doesn't actually produce x
, but an anonymous String
value that is only accessible through a reference, meaning it can be used, but not owned.
By doing z = *y
, you are attempting to own the value behind a reference. But as I said, this would require modifying x
(as it isn't valid any more afterwards), and y
has no power over x
. So this isn't possible.
Because doing z = *y
wouldn't be a problem with copyable types, as they don't require a transfer of ownership but simply get copied, Rust informs you that this isn't possible because the value that y
references doesn't implement Copy
.
z
to take ownership ofString
? You can borrow from an owned content but you cannot own an object from a borrowed contenty
has done after*y
and*y
isx
, sox
has no borrower when its ownership is moved toz
? But this doesn't seem to be how rust works. I guess (without proof)y
is still in scope until the entire statement is finished.*y
is not exactlyx
,x
is still there and owned by the current function's scope.*y
, which is*&x
, lets you access the value in the pointed memory location(&x
). If you try to assign then it tries to move that value but the value's owner isx
. If Rust lets you move that then what will happen tox
?