Skip to content

Instantly share code, notes, and snippets.

@dimitrilw
Last active July 20, 2023 19:49
Show Gist options
  • Save dimitrilw/4e2a1d5372979b5f11be1099e0a2991e to your computer and use it in GitHub Desktop.
Save dimitrilw/4e2a1d5372979b5f11be1099e0a2991e to your computer and use it in GitHub Desktop.
Go (golang) magic constants via "iota"
// use "iota" for enumerated constants, like this:
const (
a = iota // 0
b // 1
c // 2
//...
n // n
)
// ALSO, "iota" for bit-shifted config vars, to be used in bitwise OR operators
const (
OPTION_A int = 1 << iota // 1
OPTION_B // 2
OPTION_C // 4
OPTION_D // 8
)
func demoA() {
fmt.Println(OPTION_A)
fmt.Println(OPTION_B)
fmt.Println(OPTION_C)
fmt.Println(OPTION_D)
fmt.Println(OPTION_A | OPTION_C | OPTION_D)
}
// output:
// 1
// 2
// 4
// 8
// 14
// can also use custom types to have type-safety with our const values, like this:
type Color int
const (
Red Color = iota // will be Color(0)
Green // Automatically assigned as Color(1)
Blue // Automatically assigned as Color(2)
)
// we saw iota get bitshifted (above) and it can also be mathematically altered, like this
const (
_ = 1 << (iota * 10) // ignore the first value
KB // decimal: 1024 -> binary 00000000000000000000010000000000
MB // decimal: 1048576 -> binary 00000000000100000000000000000000
GB // decimal: 1073741824 -> binary 01000000000000000000000000000000
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment