#deref trait

22 messages · Page 1 of 1 (latest)

left shoal
#

you are moving out of *y so rust copies the i32

left shoal
#

to put into x

mellow sphinx
#

The signature of Deref::deref is fn(&T) -> &T::Target.
So, the dereferencing going on is “inside of a reference”.
And if you try to use the dereference in a mutation then you are using DerefMut instead — fn(&mut T) -> &mut T::Target.
Same thing, but inside of a mutable reference.

#

The notation *(y.deref()) is hiding something: that the method call might be taking an implicit reference to y.

#

So, the more accurate expansion of *y is:

*(Deref::deref(&y))

The & adds the reference that deref() needs, and the * removes the reference that deref() returns.

#

It's balanced.

tribal stratus
#

Not one of a reference, no.

#

Technically there's *boxed;, which can move out of a Box, but that one is completely magic and only works on Box

left shoal
#

deref gives you &String
you can deref it to String, but cannot move out of it because you would be moving out of a reference

tribal stratus
#

when you dereference y.deref() you're left with a string
That's not exactly true.

#

When you dereference y.deref(), you write a place expression referring to a readonly non-owning place.

#

A "place" is a location in memory, more or less.

#

If you use a place where a value is expected, it undergoes place-to-value coercion, which means it tries to become a value. It does this by moving out (for owning places) or copying out (for non-owning places).

A place produced by dereferencing a reference is non-owning, ergo it tries to copy. And it fails because String isn't Copy.

#

You could, however, write &*x.deref(). The * still produces a place, but & doesn't cause p2v coercion (in fact, & on a value would cause a value-to-place coercion: & fundamentally works on places), so you end up with a &String just fine.

mellow sphinx
#

is something similar to this happening implicitly
Yes (except the two let vs need different names so no shadowing occurs).
Or does the original v passed into fn foo still exist in the meantime.
It exists but you’re not allowed to use it.

#

Reborrowing from a reference’s referent is just like borrowing from an owned value.

#

As long as an exclusive borrow exists, you can’t have another borrow.

mellow sphinx
#

sorry, I don't follow what that means in this context

mellow sphinx
#

No, for the period that v can't be used, you can't create references to it either.

#

There are two, non-overlapping, periods where y can't be used: from lines 2-3 and from lines 4-5.

#

it'd be easier with all distinct variable names: