Closed
Description
Code
# [derive (Debug)]
pub enum Good {
A,
B,
}
# [derive (Debug)]
pub enum Bad {
A,
B(u8),
}
fn main() {
let good = Good::A;
let bad = Bad::A;
dbg!(good as u32);
dbg!(bad as u32);
}
Current output
error[E0605]: non-primitive cast: `Bad` as `u32`
--> src/main.rs:18:10
|
18 | dbg!(bad as u32);
| ^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
For more information about this error, try `rustc --explain E0605`.
Desired output
an 'as' expression can only cast an enum to an int if all of its variants are unit-like
Possibly link to the Rust Reference where this is explained in detail. https://doc.rust-lang.org/reference/items/enumerations.html#casting
Rationale and extra context
Casting an enum to an int is common for C developers. When I searched the internet for guides on how to do this in Rust, they all essentially said it just works like foo as i32
. E.g. stackoverflow, rust by example.
These guides don't explicitly say that this only works if all of the enum variants are unit-like. The compiler message in this situation did not help me to understand what had gone wrong, and googling for it and "enum" returned the same sort of results as mentioned above.
Other cases
No response
Rust Version
rustc 1.75.0 (82e1608df 2023-12-21)
binary: rustc
commit-hash: 82e1608dfa6e0b5569232559e3d385fea5a93112
commit-date: 2023-12-21
host: x86_64-unknown-linux-gnu
release: 1.75.0
LLVM version: 17.0.6
Anything else?
No response
Metadata
Metadata
Assignees
Labels
Area: Messages for errors, warnings, and lintsDiagnostics: Confusing error or lint that should be reworked.Diagnostics: Confusing error or lint; hard to understand for new users.Diagnostics: An error or lint that doesn't give enough information about the problem at hand.Relevant to the compiler team, which will review and decide on the PR/issue.