rust-lang / rust-lang/rust

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

Open
#145,376 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-const-generics A-repr-packed A-slice C-bug T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the reproducer in src/main.rs using rustc 1.89.0, comparing the fixed-capacity and const-generic PascalString examples. Investigate why the const-generic slice is treated as an unaligned packed-field reference despite u8 alignment. Done means the const-generic example receives the same valid treatment as the non-generic version, with coverage for the regression.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
43/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.