How do I get c like enums?

I have a couple of enums for which I have to implement From/Into u8. Is there a way to simply define them to have numeric values as in C.

enum Foo{
    Bar, //I want this to simply have a value of 0 or one similar to iota in golang
    Baz, //Bar +1
//so on...

It is possible to assign numeric values. More details can be found e.g. in the reference.

Enumerations - The Rust Reference

This will help with conversion into u8, not necessarily from u8.

1 Like

oh it has been such a long time since I read the book thanks:)

It’s not the book though :wink: , it’s the reference.

now noticed that.:smiley:

Some googling suggests the num-derive crate with it’s derive macro for FromPrimitive as a way to do this.

that would still require me to implement custom logic custom from and intos

I’m not sure if a From<u8> for MyEnum implementation is the most useful or appropriate thing anyways since the conversion can fail (unless your enum has exactly 256 variants). Other than these From/Into implementations you haven’t really explained what you’re after / what kind of potentially tedious code exactly you’re having that ought to be simplified.

I actually have a TryFrom and Into and I found a crate called strum which makes things super simple

Ah, that looks good ^^

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.