Constants
const, iota, typed vs untyped constants, and constant expressions evaluated at compile time.
Constants are boolean, numeric, or string values evaluated at compile time. Unlike variables, their values cannot change while a program runs.
const declares a value from a literal or another constant expression.
package main
import "fmt"
const Pi = 3.14159
const MaxRetries = 3
const ServiceName = "auth-service"
func main() {
fmt.Println(Pi, MaxRetries, ServiceName)
const localTimeout = 30 // constants can be declared inside functions too
fmt.Println(localTimeout)
}iota is a compile-time counter whose value is the index of the current constant specification, starting at 0 in each const declaration. It is often used for enum-style groups of constants.
package main
import "fmt"
type Direction int
const (
North Direction = iota // 0
East // 1
South // 2
West // 3
)
type ByteSize uint64
const (
_ = iota // ignore first value by assigning to blank identifier
KiB ByteSize = 1 << (10 * iota) // 1024
MiB // 1048576
GiB // 1073741824
)
func main() {
fmt.Println(North, East, South, West)
fmt.Println(KiB, MiB, GiB)
}An untyped constant can take the type required by its use. When a declaration gives no type, Go uses the constant kind's default type, such as int for an integer.
package main
import "fmt"
const Limit = 1000
const FixedWidth int32 = 1000
func main() {
var inferred = Limit // inferred type is int
var forAPI int64 = Limit
fmt.Printf("%T %T %d\n", inferred, forAPI, FixedWidth)
}In production
Untyped constants fit the type supplied by an assignment or function parameter. Without that context, an integer constant defaults to int, whose width depends on the target. Declare a fixed-width type when an API or serialized format requires one.