Reputation: 36339
Say I have
enum Grades { A, B, C, D, E, F }
Then I can easily use the associated value for each grade with
Grades::C as u32
However, there seems to be no opposite way. I understand that, in general, this would be a partial function, as, for example
42 as Grades
makes no sense. However, what is the idiomatic way to do this? Is it
impl From<u32> for Grades { ... }
with a panic!
if the argument is invalid? Or even
impl From<u32> for Option<Grades> { ... }
A related question, is there something like an Enum trait? As the need to convert between integer and enumerations often arises because (to my bloody beginner knowledge) there is apparently nothing that provides the functionality of Haskells Enum and Bounded typeclasses. Hence, if I need a range of Grades B..E, or the next Grade (succ B) or the previous Grade (pred E) I feel out of luck.
(The suggested question doesn't answer my question fully, since it occured to me that the deeper reason I need this functionality in the first place is most often "missing" enum functionality - that is, "missing" from the standpoint of a Haskell programmer. This is what the second part is all about.)
Upvotes: 3
Views: 276
Reputation: 1918
Although the easiest solution is probably the enum_primitive
crate (that has already been suggested), the idiomatic way to implement this yourself would be the TryFrom
trait from the standard library. This is also very close to what you have already suggested in your question. The only difference is, that this returns a Result
so that you don't have to panic!
when a wrong input is given.
Upvotes: 1
Reputation: 5325
There is a enum_primitive
crate that exports a macro enum_from_primitive!
that automatically derives FromPrimitive
which seems to do what you want.
Upvotes: 1