{
"$type": "site.standard.document",
"bskyPostRef": {
"cid": "bafyreih6n77o2k5psii5jhu5tfjbmn3mlogi5xxiogkyu32xzmqvfqavdu",
"uri": "at://did:plc:ivbknywyskln22er3nkssdhl/app.bsky.feed.post/3mkq6m5ljpib2"
},
"path": "/t/sized-or-sizeable-str-e-g-str-const-n-usize/24213#post_4",
"publishedAt": "2026-04-30T17:19:16.000Z",
"site": "https://internals.rust-lang.org",
"tags": [
"[playground]"
],
"textContent": "daniel-pfeiffer:\n\n> Is there already a way of achieving this?\n\nThis method is fully `const` as of Rust 1.88 (for `<[_]>::as_chunks`). There are other methods for supporting earlier Rust versions (e.g. unsafely assume length in `new_unchecked`). [playground]\n\n\n #[macro_export]\n macro_rules! array_str { ($lit:literal) => { const {\n const LIT: &str = $lit;\n const LEN: usize = LIT.len();\n $crate::ArrayStr::<LEN>::new(LIT).unwrap()\n }}}\n\n #[derive(Copy, Clone)]\n pub struct ArrayStr<const LEN: usize>([u8; LEN]);\n\n impl<const LEN: usize> ArrayStr<LEN> {\n #[inline]\n pub const fn new(s: &str) -> Option<&Self> {\n if let ([bytes], []) = s.as_bytes().as_chunks() {\n let ptr = core::ptr::from_ref::<[u8; LEN]>(bytes);\n // SAFETY: Self is a transparent wrapper type\n // SAFETY: bytes are UTF-8 and verified equal len\n unsafe { ptr.cast::<Self>().as_ref() }\n } else {\n None\n }\n }\n }\n\n pub const BYTES: [u8; 5] = *b\"hello\";\n pub const STR: ArrayStr<5> = *array_str!(\"hello\");\n\n\nI license any code I post here under SPDX: MIT-0 OR Apache-2.0.\n\nNote that the `Option::unwrap` occurs _at`const` time_ due to the `const` block, so there is guaranteed no runtime overhead.\n\nkpreid:\n\n> you can obtain the string length at compile time to derive the type from the literal value\n\nI see I was ninjad while putting together my example. But! Note that your example _could_ be ~~unsound~~ (EDIT: panicky) in the future if `$:literal` matchers can match custom type literals, as such a custom type could provide a `.len()` which does not match its deref-coercion to `str`. (This was more important before `$:literal`, when such macros had to take `$:expr` instead.)",
"title": "Sized (or Sizeable) str, e.g. str<const N: usize>"
}