Working with constant in Go

In Go, only Number, String, Boolean can be constant. constkeyword is used to define constant:

const (
DefaultKey string = "test"

CountryCodeVN = "vn"
CountryCodeUS = "us"

DefaultMultiplyFactor int64 = 2

Enable bool = true
Disable bool = false
)

constants are final. Once initialized, their values cannot be changed:

const defaultKey string = "test"
defaultKey = "my key" // panic

Constant can be untyped. When a constant is untyped, its precision is higher than the normal number type.

const (
bigNum = 9999999999999999999.0
)

func main() {
v := 9999999999999999999.0
fmt.Printf("%T, %T\n", bigNum, v)
fmt.Printf("%t, %t", bigNum == bigNum+1, v == v+1) // false, true
}

Playground

untyped constant can be cast to any other similar types. But its precision will be reduced:

const (
num = 200
bigNum = 9999999999999999999.0
)

type number int

func main() {
// can be cast to any similar types
var i int = num
var j int64 = num
var k float64 = num
var n number = num

fmt.Println(i, j, k, n)

// but its precision will be reduced when assign to a specific type
var bigFloat float64 = bigNum
fmt.Printf("%t, %t", bigNum == bigNum+1, bigFloat == bigFloat+1) // false, true
}

Playground

iotaidentifier can be used in constant declarations to simplify definitions of incrementing numbers:

type ByteSize float64

const (
_ = iota // ignore first value by assigning to blank identifier
KB ByteSize = 1 << (10 * iota)
MB
GB
TB
PB
EB
ZB
YB
)

Playground

Weekday using iota:

type WeekDay int8

const (
Sunday WeekDay = iota + 1
Monday
Tuesday
Wednesday
Thursday
Friday
Staturday
)

Playground

Value of iotais its position in the constblock:

const (
US = "United State"
VN = "Vietnam"
Other

Tuesday = iota
)

func main() {
fmt.Println("Tuesday:", Tuesday) // Tuesday: 3
}

Playground

If constant is defined without value, its value is same with the nearest one:

const (
US = "United State"
VN = "Vietnam"
Other
)

func main() {
fmt.Println("VN:", VN)
fmt.Println("Other:", Other) // Other: Vietnam
}

Playground