Derefercing is two parts operation. One is taking a reference to data and another is accessing the data behind the reference--which is done with the help of the dereferencing operator *
. The Deref
trait only accomplishes the first part--taking a reference and then giving it to us. Then the dereferencing operator *
follows the reference(memory address) and lets us access that data on that memory address--this part is indeed the compiler's built-in.
fn main()
{
let age: i32 = 90;
let r_age = &age; // first part: taking reference
println!("{}", *r_age); // second part: accessing the reference
}
Now if we do not have a reference how can we get access to data using the dereferencing operator *
?
fn main()
{
let age: i32 = 90;
//println!("{}", *age); // will not work, we did not take reference of age.
println!("{}", *(&age));
}
Now the Deref
trait can be implemented for our own type.
use std::ops::Deref;
fn main()
{
let d = OurOwnType(77);
println!("{}", *d);
println!("{}", *(d.deref()));
println!("{}", *(Deref::deref(&d)));
println!("{}", *(&d.0));
}
struct OurOwnType(i32);
impl std::ops::Deref for OurOwnType
{
type Target = i32;
fn deref(&self) -> &Self::Target
{
&self.0
}
}
Behind the scenes of *d
compiler invokes the deref
method from Deref
trait like d.deref()
which gives a reference, then the dereferencing operation with the help of the dereferencing operator *
lets us access the data. The Deref
trait here accomplishes the first part of giving us a reference.
x
pointing to some objecty
. You write*x
, andderef
gets called. All it does, is return yet another reference toy
, because that's what is in its sigunature (and implementation). Can you access the object now? No. Because it's still a reference. You're back where you started. This cannot be how it's implemented for references? – Masochism*x
isn't what callsderef
, so to speak.*x
dereferences an&
-ptr.Deref
allows an object that isn't a reference to pretend to be a reference, aka.Box<T>
can act like an&T
. See github.com/rust-lang/rfcs/blob/master/text/…. – AeriformAsRef
instead. Unfortunately we already have a trait with that name... – Sunburn