In Rust, how do explicit discriminants on a fieldless HttpStatus enum work with `as` casts, and why can't a u16 be cast back?
answer
- an integer behind each variant
- implicit: previous plus one, from zero
- as reads it and may truncate
- not every integer names a variant
basics
~20 sA unit-only enum may give variants values, Ok = 200; unspecified ones take the previous value plus one, starting at 0. HttpStatus::Ok as u16 reads the value, but 404u16 as HttpStatus is E0605, because most integers name no variant.
solid answer
~40 sIn a unit-only enum, `Ok = 200` sets a variant's discriminant, a variant without one takes the previous value plus one (`Created` becomes 201), and the first defaults to 0; two variants with the same value are E0081. The discriminant is logically an `isize`, and the compiler may store less: this `HttpStatus` is 2 bytes on rustc 1.99.1. `as` casts it to any integer and truncates silently when narrowing, so `ServiceUnavailable as u8` is 247, which Clippy's `cast_enum_truncation` flags. There is no cast back: an `HttpStatus` may hold only its declared values, anything else is undefined behaviour, so `404u16 as HttpStatus` is E0605 and you write a `match` returning `Option<HttpStatus>` or a `TryFrom<u16>` impl. Explicit values on an enum with data need a `repr` attribute (E0732).
code
rust · 29 lines#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HttpStatus {
Ok = 200,
Created, // implicit: previous + 1 = 201
NoContent = 204,
NotFound = 404,
ServiceUnavailable = 503,
}
impl HttpStatus {
fn code(self) -> u16 { self as u16 }
// No `as` cast exists from u16 to HttpStatus, so the way back is a match.
fn from_code(code: u16) -> Option<HttpStatus> {
match code {
200 => Some(HttpStatus::Ok),
201 => Some(HttpStatus::Created),
204 => Some(HttpStatus::NoContent),
404 => Some(HttpStatus::NotFound),
503 => Some(HttpStatus::ServiceUnavailable),
_ => None,
}
}
}
fn main() {
println!("{} {}", HttpStatus::Created.code(), HttpStatus::NotFound as i32);
println!("{:?} {:?}", HttpStatus::from_code(204), HttpStatus::from_code(418));
println!("{}", HttpStatus::ServiceUnavailable as u8); // truncates: 503 % 256
}go deeper
Recall that variants can carry explicit values, that unlisted ones count up from the previous value starting at 0, and that as reads the value out.
Explain E0081 and E0605, why as truncates silently on a narrower type, and why a checked match is the only safe way from an integer back to the enum.
Keep values that leave the process explicit so inserting a variant cannot renumber them, and put the integer-to-enum conversion at the boundary where unknown codes are handled.
Decide when an external code should be a closed enum with a checked conversion and when it should stay an integer newtype, because unknown values keep arriving from systems you do not control.
## Discriminants: the integer behind each variant Every enum value has a **discriminant**, an integer the program uses to tell which variant a value holds. Under the default representation the Reference says the discriminant "is interpreted as an `isize` value", while "the compiler is allowed to use a smaller type" in memory. For a **unit-only** enum (every variant a bare name, like `HttpStatus`) the discriminant is the whole value, and you can choose it. ## Assigning values The rules for a unit-only enum such as `HttpStatus`: 1. A variant may take an explicit value with `= constant expression`: `Ok = 200`. 2. A variant without one gets the previous variant's value plus one, so `Created` after `Ok = 200` is **201**. 3. If the first variant has no value, it is **0**: discriminants count from zero, not one. 4. Two variants may not share a value: `Ok = 200, Accepted = 200` fails with **E0081**, "discriminant value `200` assigned more than once". On rustc 1.99.1 for a 64-bit target, the `HttpStatus` in the example (values 200 to 503) is 2 bytes: the compiler chose a 2-byte integer, the smallest that holds 503. That size is what the compiler chose, not something the default representation promises; fixing the storage type is the job of the `#[repr(u16)]` family of attributes, which is a layout topic of its own. An enum whose variants carry data can take explicit values only with such a `repr` attribute: `enum PaymentEvent { Heartbeat = 0, Authorized(u64) = 1 }` fails with **E0732**, "`#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants". ## Casting out with `as` A unit-only enum casts to any integer type with `as`. The cast reads the discriminant: | Expression | Result | |---|---| | `HttpStatus::Created as u16` | `201` | | `HttpStatus::NotFound as i32` | `404` | | `HttpStatus::ServiceUnavailable as u8` | `247`, silently truncated (503 keeps its low 8 bits) | | `PaymentEvent::Heartbeat as u8` (enum with data) | E0605, non-primitive cast | Two details trip people up: - **Truncation is silent.** `as` never checks range; debug-build overflow checks do not apply to it. rustc compiles `ServiceUnavailable as u8` without a warning, and Clippy's `cast_enum_truncation` lint, warn-by-default, is what catches it. Casting numbers in general is covered with the numeric types. - **Only fieldless enums cast.** For an enum with data, rustc's E0605 note says an `as` expression "can be used to convert enum types to numeric types only if the enum type is unit-only or field-less". To compare which variant two data-carrying values hold, use `std::mem::discriminant`, which returns an opaque, comparable value rather than a number. Wrapping the cast in a method, `fn code(self) -> u16 { self as u16 }`, keeps the target type in one place. ## No cast back, and why `404u16 as HttpStatus` fails with **E0605**, "non-primitive cast: `u16` as `HttpStatus`". The reason is validity, not syntax. The Reference's list of undefined behaviour says an enum "must have a valid discriminant": an `HttpStatus` may hold only 200, 201, 204, 404 or 503, and any other bit pattern in that memory is undefined behaviour. Most `u16` values name no variant, so an unchecked cast cannot exist in safe code. The checked conversion is yours to write: - a `match` from the integer to `Option<HttpStatus>`, with `_ => None` for every unknown code, as in the example; - or an implementation of `TryFrom<u16>` around the same `match`, so callers can write `HttpStatus::try_from(code)` (conversion traits are a topic of their own). Reaching for `std::mem::transmute` on an unchecked integer is the wrong shortcut: it is unsafe, and it is undefined behaviour the first time a server sends 418. The asymmetry is deliberate. Every `HttpStatus` has exactly one number, so the cast out cannot fail; many numbers have no `HttpStatus`, so the way in must be able to say "unknown", and only a function returning `Option` or `Result` can. ## Where explicit values matter Explicit discriminants are worth writing when the number means something outside the program: an HTTP status, a protocol opcode, a database code. Implicit values are positional, so inserting a variant shifts every implicit value after it. If `Accepted` is added between `Created` and `NoContent`, it becomes 202 and `NoContent` stays 204 only because it is explicit. Values that leave the process should therefore all be explicit, and the way back in should always go through a checked `match`.
- If someone inserts `Accepted` between `Created` and `NoContent`, what happens to the values?`Accepted` takes 202 implicitly, one more than `Created`'s 201. `NoContent` stays 204 only because it is explicit; had it been implicit, it would now be 203. Every implicit value after an insertion moves, so values that cross a wire or reach a database should all be written out.
- How do you check which variant two `PaymentEvent` values hold when the enum carries data and cannot be cast?Compare `std::mem::discriminant(&a) == std::mem::discriminant(&b)`. It returns an opaque `Discriminant<PaymentEvent>` that implements `Eq` and `Hash` and ignores the payloads. It cannot be turned into the number, and its documentation says transmuting it to an integer is undefined behaviour.
- 404u16 as HttpStatus works as long as 404 is one of the variants.
- Casting a 503 variant to u8 is a compile error because it does not fit.
- Implicit discriminants count from 1, like positions in a list.
- Any enum can be cast with as, including ones whose variants carry data.
- Transmuting an unchecked u16 into HttpStatus is a fine replacement for a cast back.