| 1 | # What `#[derive(TryFrom)]` generates |
| 2 | |
| 3 | Derive `TryFrom` allows you to convert enum discriminants into their corresponding variants. |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | ## Enums |
| 9 | |
| 10 | By default, a `TryFrom<isize>` is generated, matching the [type of the discriminant](https://doc.rust-lang.org/reference/items/enumerations.html#discriminants). |
| 11 | The type can be changed with a `#[repr(u/i*)]` attribute, e.g., `#[repr(u8)]` or `#[repr(i32)]`. |
| 12 | Only field-less variants can be constructed from their variant, therefore the `TryFrom` implementation will return an error for a discriminant representing a variant with fields. |
| 13 | |
| 14 | ```rust |
| 15 | # use derive_more::TryFrom; |
| 16 | # |
| 17 | #[derive(TryFrom, Debug, PartialEq)] |
| 18 | #[try_from(repr)] |
| 19 | #[repr(u32)] |
| 20 | enum Enum { |
| 21 | ImplicitZero, |
| 22 | ExplicitFive = 5, |
| 23 | FieldSix(usize), |
| 24 | EmptySeven{}, |
| 25 | } |
| 26 | |
| 27 | assert_eq!(Enum::ImplicitZero, Enum::try_from(0).unwrap()); |
| 28 | assert_eq!(Enum::ExplicitFive, Enum::try_from(5).unwrap()); |
| 29 | assert_eq!(Enum::EmptySeven{}, Enum::try_from(7).unwrap()); |
| 30 | |
| 31 | // Variants with fields are not supported, as the value for their fields would be undefined. |
| 32 | assert!(Enum::try_from(6).is_err()); |
| 33 | ``` |