diff --git a/strum/src/lib.rs b/strum/src/lib.rs index 3b5af9c..90f2d75 100644 --- a/strum/src/lib.rs +++ b/strum/src/lib.rs @@ -217,6 +217,15 @@ pub trait VariantNames { const VARIANTS: &'static [&'static str]; } +/// A trait for retrieving the enum generated by [`EnumDiscriminants`] from an associated +/// Type on the original enumeration. This trait can be autoderived by `strum_macros`. +pub trait IntoDiscriminant { + /// Enum listing the same variants as this enum but without any data fields + type Discriminant; + + fn discriminant(&self) -> Self::Discriminant; +} + /// A trait for retrieving a static array containing all the variants in an Enum. /// This trait can be autoderived by `strum_macros`. For derived usage, all the /// variants in the enumerator need to be unit-types, which means you can't autoderive @@ -248,7 +257,7 @@ DocumentMacroRexports! { AsRefStr, Display, EnumCount, - EnumDiscriminants, + IntoDiscriminant, EnumIter, EnumMessage, EnumProperty, diff --git a/strum_macros/src/macros/enum_discriminants.rs b/strum_macros/src/macros/enum_discriminants.rs index f7d6372..aee4bc6 100644 --- a/strum_macros/src/macros/enum_discriminants.rs +++ b/strum_macros/src/macros/enum_discriminants.rs @@ -22,6 +22,7 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result { // Derives for the generated enum let type_properties = ast.get_type_properties()?; + let strum_module_path = type_properties.crate_module_path(); let derives = type_properties.discriminant_derives; @@ -165,6 +166,14 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result { #(#discriminants),* } + impl #impl_generics #strum_module_path::IntoDiscriminant for #name #ty_generics #where_clause { + type Discriminant = #discriminants_name; + + fn discriminant(&self) -> Self::Discriminant { + >::from(self) + } + } + #impl_from #impl_from_ref })