Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between `*` operator and `deref()` method? [duplicate]

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?

like image 313
ZyS Avatar asked Oct 19 '25 04:10

ZyS


1 Answers

* 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.

like image 93
Chayim Friedman Avatar answered Oct 22 '25 05:10

Chayim Friedman



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!