How to mix iota and values

648 views Asked by At

In a Go enum containing iota, how is it possible to force some values, yet auto-incrementing others?

For example, in this source code,

const (
    SUCCESS         int = iota
    ERROR_UNKNOWN       = 3
    ERROR_ARGS
    NOFILES             = 50
    ERROR_OPEN_FILE
    ERROR_BADFILENAME
)

ERROR_ARGS=ERROR_UNKNOWN, where I expected it to be ERROR_UNKNOWN + 1 .

Is there a way to achieve mixing auto-increment and 'forcing' values, without the _ method, that is cumbersome for big gaps like here (4 to 50, inserting 46 _ lines...)

Clarifying after first answer below: Values must always 'go forwards', auto-incrementing even after a forced value.

1

There are 1 answers

2
S4eed3sm On

It's not possible to set ERROR_ARGS = ERROR_UNKNOWN + 1 by iota, you can mix automatic increment with manual value like this:

const (
    SUCCESS         int = iota
    ERROR_UNKNOWN       = 3
    ERROR_ARGS          = iota
    NOFILES             = 50
    ERROR_OPEN_FILE     = iota
    ERROR_BADFILENAME
)

Values will be:

0
3
2
50
4
5