Go by Example

Constants

const, iota, typed vs untyped constants, and constant expressions evaluated at compile time.

Constants are boolean, numeric or string values that Go works out before the program runs. Unlike variables, a constant cannot change while the 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 gives each line in a const group a number starting at zero. It is often used when a group of related constants needs distinct values.

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 has no specific Go type until it is used, so Go can use the type needed by that operation. If nothing supplies a type, Go chooses a default 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

If you need an integer to have the same size on every computer, declare a fixed-size type such as int32 or int64 instead of int.

Enjoyed this? Get more software craft delivered to your inbox.