#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_box", issue = "92521")]
impl<T: ?Sized, A: Allocator> const Deref for Box<T, A> {
type Target = T;
fn deref(&self) -> &T {
&**self // multiple times of the dereference
}
}
let d = Box::new(10);
let c = d.deref(); // get a reference to i32
As a contrast
struct Wrapper(i32);
impl Deref for Wrapper{
type Target = i32;
fn deref(&self) -> &Self::Target { // Compiler warns that "recursive call site"
&**self
}
}
Is &**self in the implementation of Deref for Box the compiler magic?
These impls are actually used when referencing them through generics. For example
use core::ops::Deref;
fn foo(a: &impl Deref<Target = u32>) -> &u32 {
&**a // don't know the concrete type of a, so has to refer to Deref::deref
}
pub fn bar() {
foo(&Box::new(0));
}
What basically happens is that if the type is know to be a Box, it replaces the deref with a compiler builtin deref operation and if not inserts a real Deref::deref call. Inside the Deref impl for Box, it knows that it is a Box and as such does replace it with a builtin deref operation. The same happens for other operations with builtin impls, like math on integers and floats.