Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ENUMs for custom types in GO

Tags:

enums

go

iota

I am trying to generate an enum for a type I defined

type FeeStage int

From this I learned that I can use iota to create an enum based on this type

const(
     Stage1 FeeStage = iota
     Stage2 
     Stage3
)

However, manipulating the actual values of the enum is rather cumbersome and error prone

const(
     Stage1 FeeStage = iota           // 0
     Stage2          = iota + 6       // 7
     Stage3          = (iota - 3) * 5 // -5
)

Is there a way to automatically convert a list of ENUMs with custom values to a certain type. This is what I was using before but only converts the first member of the constant to the custom type.

const(
     Stage1 FeeStage = 1
     Stage2          = 2
     Stage3          = 2
)

Here is a playground with a similar result

like image 927
Benjamin Kadish Avatar asked Mar 29 '16 15:03

Benjamin Kadish


People also ask

Can I use enum as type?

You can do this because enums are compiled to JavaScript objects, so they also have a value representation in addition to being types. direction can therefore only be set to a member of the CardinalDirection enum.

Does Go support enums?

Enums are a powerful feature with a wide range of uses. However, in Golang, they're implemented quite differently than most other programming languages. Golang does not support enums directly. We can implement it using iota and constants .

Why are there no enums in go?

Unfortunately, enums in Go aren't as useful due to Go's implementation. The biggest drawback is that they aren't strictly typed, thus you have to manually validate them. Having a wide range of usages, ENUMs are a powerful feature of many languages. They let you define strict values of data you expect.


1 Answers

There's no way beyond either using iota and automatic enums, or doing the most straightforward thing:

const(
     Stage1 FeeStage = 1
     Stage2 FeeStage = 2

     // or another syntax with same results
     Stage3 = FeeStage(2)
)

which IMHO is less cumbersome than doing stuff like iota + 5 which as you said is really bad.

I usually either use iota if the value is not important beyond the context of the program, or explicit typing if I need the values to be used in a protocol or something.

Though I have to say sometimes just using ints or strings is good enough, it depends on the context. See for example the http status codes in the standard library. They don't have a special type.

like image 91
Not_a_Golfer Avatar answered Oct 19 '22 21:10

Not_a_Golfer