{
"$type": "site.standard.document",
"bskyPostRef": {
"cid": "bafyreibbpfv2fdjkyqxk3yhlnrmw7p3ec6tszfpsz5nj5i3k5epmbydwf4",
"uri": "at://did:plc:ivbknywyskln22er3nkssdhl/app.bsky.feed.post/3mkq6mciqvq22"
},
"path": "/t/sized-or-sizeable-str-e-g-str-const-n-usize/24213#post_3",
"publishedAt": "2026-04-30T17:06:12.000Z",
"site": "https://internals.rust-lang.org",
"textContent": "daniel-pfeiffer:\n\n> Is there already a way of achieving this?\n\nGiven that you’re already using macros-pretending-to-be-literals, you can obtain the string length at compile time to derive the type from the literal value:\n\n\n #[repr(transparent)]\n pub struct SizStr<const LEN: usize>([u8; LEN]);\n\n impl<const LEN: usize> SizStr<LEN> {\n pub const fn strict_from_ref(s: &str) -> &Self {\n // as long as you use the macro, this assertion cannot fail\n assert!(s.len() == LEN);\n // SAFETY: Self is a transparent wrapper, the input bytes are UTF-8,\n // and we checked the length.\n unsafe { &*(&raw const *s).cast::<Self>() }\n }\n\n pub fn as_str(&self) -> &str {\n // SAFETY: Length and utf-8 was checked at construction time\n unsafe { core::str::from_utf8_unchecked(self.as_array()) }\n }\n\n pub fn as_array(&self) -> &[u8; LEN] {\n &self.0\n }\n }\n\n macro_rules! sizstr {\n ($text:literal) => {\n SizStr::<{ $text.len() }>::strict_from_ref($text)\n };\n }\n\n fn main() {\n let s: &'static SizStr<5> = sizstr!(\"hello\");\n println!(\"{:?} {:?}\", s.as_str(), s.as_array());\n\n // this will be a type error, not a const eval error!\n // let _: &'static SizStr<6> = sizstr!(\"hello\");\n }\n",
"title": "Sized (or Sizeable) str, e.g. str<const N: usize>"
}