Skip to content

RFC: Open up your enum with an unnamed variant - #3894

Open
kupiakos wants to merge 44 commits into
rust-lang:masterfrom
kupiakos:unnamed-variants
Open

RFC: Open up your enum with an unnamed variant#3894
kupiakos wants to merge 44 commits into
rust-lang:masterfrom
kupiakos:unnamed-variants

Conversation

@kupiakos

@kupiakos kupiakos commented Dec 9, 2025

Copy link
Copy Markdown

View all comments

Enable ranges of enum discriminants to be claimed ahead of time with an unnamed enum variant. This requires all users of that enum to consider those values as valid - including within the declaring crate.

This is useful for any situation in which recompiling an enum to handle new discriminant values is infeasible, and using a newtype integer is unergonomic due to the type's intended nature as a set of enumerated values. This includes FFI, Protobuf, and embedded syscalls.

If an enum is valid for every discriminant (it has no niches), it is an open enum and may be as cast from its explicit backing integer. For example:

#[repr(u32)]     // Fruit is represented by any `u32` due to the unnamed *open variant* below.
enum Fruit {
    Apple,       // Apple is represented with 0u32.
    Orange,      // Orange is represented with 1u32.
    Banana = 4,  // Banana is represented with 4u32.
    _ = ..,      // Unnamed variants in `Fruit` are represented with the
                 // remaining discriminants in `u32`.
}
// Using an `as` cast from `u32`, since it is an open enum.
let fruit = 3 as Fruit;

// Does not match any of the known variants.
match fruit {
    Fruit::Apple | Fruit::Orange | Fruit::Banana => unreachable!(),
    // This wildcard branch is required for all exhaustive matches of `Fruit`.
    // `fruit` preserves its value casting back to `u32`.
    _ => assert_eq!(fruit as u32, 3),
}

While writing this RFC I was not aware of the recent work on a similar RFC by @madsmtm. I considered using an attribute to make an open enum before I had learned about this RFC - I explain why I chose unnamed variants instead in the Alternatives.

@rustbot label T-lang

Important

When responding to RFCs, try to use inline review comments (it is possible to leave an inline review comment for the entire file at the top) instead of direct comments for normal comments and keep normal comments for procedural matters like starting FCPs.

This keeps the discussion more organized.

Rendered.

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

T-lang Relevant to the language team, which will review and decide on the RFC.

Projects

None yet

Development

Successfully merging this pull request may close these issues.