0

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
ymudyruc
  • 77
  • 9
  • Are you looking for this? https://go.dev/play/p/zd-6bY6ID9w – mkopriva Dec 31 '21 at 10:43
  • @mkopriva Nice idea! Not ideally, because of the count that is not so automatic, but rather close to the goal. – ymudyruc Dec 31 '21 at 10:50
  • IMO, don't do that. It will be very confusing to read that code for most people. Either use iota for everything, or for nothing, if code readability means anything to you. – Jonathan Hall Dec 31 '21 at 11:30
  • The marked duplicate shows examples to automatically calculate the offset. Easiest is to break the constant group, but you can also achieve automatic offset calculation in a single group if you add "sentinel" constant values used as offset in subsequent declarations. – icza Dec 31 '21 at 11:35

1 Answers1

2

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
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
S4eed3sm
  • 1,398
  • 5
  • 20