ENUM for custom types in GO

I am trying to create an enumeration for a specific type I

type FeeStage int

From this, I found out that I can use iota to create an enumeration based on this type

const(
     Stage1 FeeStage = iota
     Stage2 
     Stage3
)

However, manipulating actual enum values โ€‹โ€‹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 an ENUM list with custom values โ€‹โ€‹to a specific type. This is what I used before, but only converts the first member of the constant to a custom type.

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

Here is a playground with a similar result

+4
source share
3 answers

iota :

const(
     Stage1 FeeStage = 1
     Stage2 FeeStage = 2

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

, iota + 5, , , .

iota, , , , - .

, ints , . ., , http . .

+6

, , , , .

iota , , , . .

, .

+2

. .

, , :

const n int64 = 3 // n will be a typed constant, its type will be int64

, :

const x = int16(3) // x will be a typed constant, its type will be int16

, :

const i = 1 // i will be an untyped integer constant

, i (, fmt.Printf("%T", i), int), , , ( fmt.Println() interface{}) - int .

const ( ). , ( ).

, :

const(
    Stage1 FeeStage = iota
    Stage2 
    Stage3
)

:

const (
    Stage1 FeeStage = iota
    Stage2 FeeStage = iota
    Stage3 FeeStage = iota
)

3 : Stage1, Stage2 Stage3, FreeStage.

:

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

, , Stage1 ( FreeStage), ! , ( )!

, : - :

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

, , Stage2 Stage3 . , , const:

ConstSpec      = IdentifierList [ [ Type ] "=" ExpressionList ] .

:

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

? , . , Not_a_Golfer:

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

All Articles