Skip to content

Match guard creates reference to scrutinee, observable via repr(packed) #144982

@theemathas

Description

@theemathas

I'm not sure if this is a bug or working as intended, but I'm filing this issue because I find the behavior to be rather strange.

I tried this code:

#[repr(packed)]
#[derive(Copy, Clone)]
struct Thing {
    a: i16,
    b: i32,
}

fn foo() {
    let x = Thing { a: 1, b: 1 };
    match x.b {
        _temp if true => {}
        _ => {}
    }
}

This produces the following error, even though I'm not explicitly creating a reference anywhere:

error[E0793]: reference to packed field is unaligned
  --> src/lib.rs:11:9
   |
11 |         _temp if true => {}
   |         ^^^^^
   |
   = 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`.

See also #144939, which probably has the same root cause.

@rustbot labels +A-patterns +A-repr-packed

Meta

Reproducible on the playground with version 1.91.0-nightly (2025-08-05 ec7c02612527d185c379)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-patternsRelating to patterns and pattern matchingA-repr-packedArea: the naughtiest reprC-bugCategory: This is a bug.needs-triageThis issue may need triage. Remove it if it has been sufficiently triaged.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions