In Go, iota is a special constant used to assign sequential integers to enumerated constants within a constant group. However, there are times when it's necessary to skip assigning iota values to certain constants. Here are three approaches:
If the constants are within the same group, you can manually shift the iota with a constant, leaving empty initialization expressions for those constants you want to skip:
const ( APPLE = iota ORANGE PEAR BANANA = iota + 96 // 96 is added manually to get 99 GRAPE ) fmt.Println(APPLE, ORANGE, PEAR, BANANA, GRAPE)
This approach will produce the desired output: 0, 1, 2, 99, 100. However, changing the order or inserting new constants before BANANA will affect the values of BANANA and subsequent constants.
To avoid unexpected value changes, break the constant group and start a new one:
const ( APPLE = iota ORANGE PEAR ) const ( BANANA = iota + 99 // Iota resets to 0 GRAPE ) fmt.Println(APPLE, ORANGE, PEAR, BANANA, GRAPE)
This will also produce the same output, and inserting new constants before BANANA will not affect the values of BANANA and subsequent constants.
To maintain the single constant group while skipping values, introduce a constant where the break should occur and subtract its value from iota in the next line:
const ( APPLE = iota ORANGE PEAR _BREAK BANANA = iota - _BREAK + 98 // Continues from 98 + 1 = 99 GRAPE ) fmt.Println(APPLE, ORANGE, PEAR, BANANA, GRAPE)
This approach ensures that changing the order or inserting new constants before BANANA will not affect the values of BANANA and subsequent constants. To simplify the offset calculation, _BREAK can be initialized with iota 1, so the offset to apply to the next constant is the value of _BREAK itself:
const ( APPLE = iota ORANGE PEAR _BREAK = iota + 1 BANANA = iota - _BREAK + 99 // Continues from 99 GRAPE )
The above is the detailed content of How Can I Skip Iota Values When Assigning Sequential Integers to Constants in Go?. For more information, please follow other related articles on the PHP Chinese website!