Skip to content

Add impl TryFrom<T> for E where E is a C-like #[repr(T)] enum #2783

Open
@canndrew

Description

@canndrew

This is a problem that has come up a lot. The most recent discussion I could find about it is the internals thread here, but that thread has been locked and I figured this should probably have an "official" issue somewhere.

There's currently no (good) way to convert from an enum integer discriminant value to the enum itself. Enums should support deriving TryFrom for this purpose. eg.

#[repr(u32)]
#[derive(TryFrom)]
enum MyCoolEnum {
    Foo = 1,
    Bar = 2,
}

let x: u32 = ... ;
let my_cool_enum = MyCoolEnum::try_from(x).expect("invalid discriminant!");

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-deriveDeriving related proposals & ideasT-langRelevant to the language team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions