Why does unwrapping `Option<&mut &mut SomeStruct>` work while unwrapping `Option<&mut SomeStruct>` fails

struct XXX {
    next: Option<&'static mut XXX>,
}

fn foo(xxx: &mut XXX) -> *mut XXX {
    *xxx.next.as_mut().unwrap() as *mut XXX // this compiles
    // xxx.next.unwrap() as *mut XXX // this fails
}

fn main() {
    let mut value = XXX { next: None };
    foo(&mut value);
}

I get that xxx.next.unwrap() fails because unwrap takes the value and &mut XXX is not copiable. But I don't understand why it works with as_mut()....

Although it's true that a mutable reference cannot be copied, it can still be reborrowed, producing a sub-reference. That's what's happening.

2 Likes