Can someone help me understand the Box::leak() implementation?

76 points BlueMoonMelinda

\[Solved\]
Here is how it's implemented:

pub const fn leak<'a>(b: Self) -> &'a mut T
where
    A: 'a,
{
    unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
}

In my head I parse it as:

&mut (*((mem::ManuallyDrop::new(b).0).as_ptr()))

But mem::ManuallyDrop is not a tuple/tuple struct:

pub struct ManuallyDrop<T: ?Sized> {
    value: T,
}

So how does ".0" work? My best guess is that there is some kind of Trait which allows using it(like Index for indexing) but I wasn't able to find such.

Edit: From the comments I found that it should be parsed like this:

&mut (((*mem::ManuallyDrop::new(b)).0).as_ptr())

which makes sense since Box is a tuple struct but then what is the purpose of calling as\_ptr() after that?Edit 2: I think I have a reasonable guess for what is happening(Edit 3: now confirmed by comments). Looking at the Box type:

pub struct Box<
    T: ?Sized,
    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
>(Unique<T>, A);

the first element is a Unique<T> which is some private type from the standard library. I managed to find a documentation page for as\_ptr() and (it should have been obvious) it returns a raw pointer to the data. So my guess is that this pointer gets automatically dereferenced and then returned as a mutable reference.