Why does ref-to-ptr cast need a dereference?

For instance,

pub fn g(r: &'static u32) -> *const u32 {
    let p = r as *const _;
    p
}

is converted to the following in MIR

fn g(_1: &u32) -> *const u32 {
    debug r => _1;
    let mut _0: *const u32;
    scope 1 {
        debug p => _0;
    }

    bb0: {
        _0 = &raw const (*_1);
        return;
    }
}

Why is the reference _1 reborrowed but directly assigned to a pointer type? I understand implicit reborrowing in the context of mutable references but I am not aware of this happening with shared references.

A &raw to the place *_1 is created to avoid the need to create a reference in the general case.

Here's the RFC.

The stable/public facing side of avoiding creating reference (which have validity requirements) are macros like addr_of. Or just the methods on *const _ and *mut _.

I doubt there are many if any stability guarantees phrased in terms of MIR, by the way.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.