Anyway to construct a reference to a #[repr(transparent)] NewType in a const context on stable Rust

For example say I want to newtype str

struct Example(str);

There doesn't seem to be a way to construct this type in a const context. The following works fine without const but is not allowed with it.

impl Example {
    pub const fn new(inner: &str) -> &Self {
        let ptr = inner as *const str as *const Self;
        // Safety: `Self` is #[repr(transparent)]
        unsafe { &*ptr }
    }
}

Is there any work around for this? (Besides changing Example to Example<'a>(&'a str)

Not in const contexts. Right now const is intentionally limited and doesn't support any direct unsafe code. You can preview support for future const features in nightly (including pointer dereference). Second custom unsized types are limited until something like RFC 2580 is implemented

I think it is possible to construct the new type in a const but not in a const function. This is less ergonomic and potentially more error prone if you're using it in multiple places.

#[repr(transparent)]
struct Example(str);

fn main() {
    const TEXT: &str = "hello";
    // Safety: Example is `repr(transparent)` and TEXT is an &str,
    // therefore they are memory compatible.
    const EXAMPLE: &Example = unsafe { std::mem::transmute(TEXT) };
}

Playground.

2 Likes

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.