TheDeveloperBlog.com


Golang Const Examples

Consts. Some things do not change. ID equals 1225. This is a constant value, not something that will be altered at runtime. We use a const block for it.


Constant creation. With iota we gain a way to generate groups of constants based on expressions. With it, we can create an entire group of constants. This reduces bugs.


An example. Here we introduce the const keyword in a block of enumerated constants. We do not use all the features of const here. We declare three names and give them values.

Tip: The equals signs should lineup vertically in consts. This is achieved with the Gofmt program.

Tip 2: We can use these constants as values in a Go program by directly inserting the names.

Based on:

Golang 1.4

Golang program that uses const

package main

import "fmt"

const (
    Cat  = 10
    Dog  = 20
    Bird = 30
)

func main() {
    // Use our constants.
    fmt.Println(Cat)
    fmt.Println(Dog)
    fmt.Println(Bird)
}

Output

10
20
30

Iota. This is an enumerator for const creation. The Go compiler starts iota at 0 and increments it by one for each following constant. We can use it in expressions.

Caution: We cannot use iota in an expression that must be evaluated at runtime—a const is determined at compile-time.

Tip: The term iota is like beta: it stands for the letter "I" in Greek, just as beta stands for B.

In some programming languages iota is used to represent an array of consecutive integers.

Iota: Wikipedia
Golang program that uses iota in const

package main

import "fmt"

const (
    Low = 5 * iota
    Medium
    High
)

func main() {
    // Use our iota constants.
    fmt.Println(Low)
    fmt.Println(Medium)
    fmt.Println(High)
}

Output

0
5
10

Var, variables. We can declare variables in a var block. Here variables are initialized at runtime, and they can be reassigned in methods. They can be used throughout the program.

Golang program that uses var

package main

import (
    "fmt"
    "time"
)

var (
    Month = time.Now().Month()
    Year = time.Now().Year()
)

func main() {
    // Use variables declared in var.
    fmt.Println(Month)
    fmt.Println(Year)
}

Output

January
2015

Cannot assign const. A constant name cannot be assigned to another value. It is not a variable. The Go compiler will report an error here. With var, the program will compile.

Golang program that causes assignment error

package main

const (
    Normal = 1
    Medium = 2
)

func main() {
    Medium = 3
}

Output

C:\programs\file.go:13: cannot assign to Medium

With const and iota, Go provides compile-time code generation features. We can specify many constants with just an expression. With var we separate variables into a block.