Skip to content

Compiler doesn’t allow creating u8 slices when using const generics #145376

@gralpli

Description

@gralpli

This compiles:

#[repr(C, packed)]
struct PascalString10 {
    len: u8,
    buf: [u8; 10],
}

fn foo(s: &PascalString10) -> &str {
    str::from_utf8(&s.buf[0..s.len as usize]).unwrap()
}

But if I use const generics it doesn’t anymore:

#[repr(C, packed)]
struct PascalString<const CAPACITY: usize> {
    len: u8,
    buf: [u8; CAPACITY],
}

fn bar<const CAPACITY: usize>(s: &PascalString<CAPACITY>) -> &str {
    str::from_utf8(&s.buf[0..s.len as usize]).unwrap()
}

I get the error:

error[E0793]: reference to packed field is unaligned
  --> src/main.rs:18:21
   |
18 |     str::from_utf8(&s.buf[0..s.len as usize]).unwrap()
   |                     ^^^^^
   |
   = note: packed structs are only aligned by one byte, and many modern architectures penalize unaligned field accesses
   = note: creating a misaligned reference is undefined behavior (even if that reference is never dereferenced)
   = help: copy the field contents to a local variable, or replace the reference with a raw pointer and use `read_unaligned`/`write_unaligned` (loads and stores via `*p` must be properly aligned even when using raw pointers)

For more information about this error, try `rustc --explain E0793`.

Since u8 slices have an alignment of 1 (for all values of CAPACITY) and the first code block works, I think the second one should too.

Meta

rustc --version --verbose:

rustc 1.89.0 (29483883e 2025-08-04)
binary: rustc
commit-hash: 29483883eed69d5fb4db01964cdf2af4d86e9cb2
commit-date: 2025-08-04
host: x86_64-unknown-linux-gnu
release: 1.89.0
LLVM version: 20.1.7

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-genericsArea: const generics (parameters and arguments)A-repr-packedArea: the naughtiest reprA-sliceArea: `[T]`C-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions