Constants
Examples in
Go
Go supports constants of character, string, boolean, and numeric values.
package main
// Declare two individual constants. Yes,
// non-ASCII letters can be used in identifiers.
const π = 3.1416
const Pi = π // equivalent to: Pi == 3.1416
// Declare multiple constants in a group.
const (
No = !Yes
Yes = true
MaxDegrees = 360
Unit = "radian"
)
func main() {
// Declare multiple constants in one line.
const TwoPi, HalfPi, Unit2 = π * 2, π * 0.5, "degree"
}
// The iota keyword represents successive integer constants 0, 1, 2,…
// It resets to 0 whenever the word const appears in the source code,
// and increments after each const specification.
const (
C0 = iota
C1
C2
)
fmt.Println(C0, C1, C2) // "0 1 2"
// To start a list of constants at 1 instead of 0, you can use iota in an arithmetic expression.
const (
C1 = iota + 1
C2
C3
)
fmt.Println(C1, C2, C3) // "1 2 3"
const (
C1 = iota + 1
_
C3
C4
)
fmt.Println(C1, C3, C4) // "1 3 4"
// Complete enum type with strings [best practice]
type Direction int
const (
North Direction = iota
East
South
West
)
func (d Direction) String() string {
return [...]string{"North", "East", "South", "West"}[d]
}