Skip to content

Error message of casting a reference of #[repr(Int)] enum to Int is lacking details #151116

@xremming

Description

@xremming

Code

#[repr(u8)]
enum Priority {
    High = 255,
    Normal = 127,
    Low = 1,
}

fn main() {
    let priority = &Priority::Normal;
    let priority = priority as u8;
}

Current output

Compiling playground v0.0.1 (/playground)
error[E0606]: casting `&Priority` as `u8` is invalid
  --> src/main.rs:10:20
   |
10 |     let priority = priority as u8;
   |                    ^^^^^^^^^^^^^^
   |
   = help: cast through a raw pointer first

For more information about this error, try `rustc --explain E0606`.
error: could not compile `playground` (bin "playground") due to 1 previous error

Desired output

Compiling playground v0.0.1 (/playground)
error[E0606]: casting `&Priority` as `u8` is invalid
  --> src/main.rs:10:20
   |
10 |     let priority = priority as u8;
   |                    ^^^^^^^^^^^^^^
   |
   = help: cast through a raw pointer first
   = help: try dereferencing before the cast `*priority as u8`

For more information about this error, try `rustc --explain E0606`.
error: could not compile `playground` (bin "playground") due to 1 previous error

Rationale and extra context

The error explanation already has the correct example snippet. Getting it directly in the error message would a good improvement for usability.

When casting, keep in mind that only primitive types can be cast into each other. Example:

let x = &0u8;
let y: u32 = *x as u32; // We dereference it first and then cast it.

"Cast through a raw pointer first" is quite confusing, especially since (many) Rust programmers rarely encounter or use raw pointers themselves and because priority as *const u8 as u8 doesn't actually work (error[E0606]: casting &Priorityas*const u8 is invalid).

There are many other errors that give a useful example on what you probably meant but I couldn't think of any right now so the desired output is not formatted in the same "example style".

Other cases

Removing the #[repr(Int)] from the enum has the same error.

It's also a bit confusing that casts to integers work at all without the repr but I guess that's just a property of how field-less enums work.

Rust Version

rustc 1.94.0-nightly (2850ca829 2026-01-13)

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions