What I've been told is that once an object (in this cast sth
) implements the Drop
trait then it can use *
operator to call its deref()
method. So I think the result of using *
should be the same as the result of explicitly call deref()
. But I find in some cases the two results are not equal. For example:
use std::ops::Deref;
fn main() {
let sth = Box::new(5);
println!("{:p}", sth.deref());
println!{"{:?}", *sth};
}
I searched the docs and know that the signature of deref()
of Box
is (&self)->&T
. That means it should return a reference of inner value. However, *sth
looks like it is returning the inner value directly. Why are the two results not equal?
*
is not the same as v.deref()
(or more exactly Deref::deref(&v)
) - it's more like *Deref::deref(&v)
(note the *
).
Regarding Box
specifically, it can move out of it, like:
let s = Box::new(String::new());
let moved_out = *s;
// s; // Error, moved out of the `Box`.
In either type, it creates a place - it can be *Deref::deref(&v)
or *DerefMut::deref_mut(&v)
, depending on whether mutable access is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With