#deref trait
22 messages · Page 1 of 1 (latest)
to put into x
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.
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
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
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.
is something similar to this happening implicitly
Yes (except the twolet 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.
sorry, I don't follow what that means in this context