Working with constant in Go
In Go, only Number, String, Boolean can be constant. const
keyword 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
}
Playgrounduntyped 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
}
Playgroundiota
identifier 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
)
PlaygroundWeekday using iota:
type WeekDay int8
const (
Sunday WeekDay = iota + 1
Monday
Tuesday
Wednesday
Thursday
Friday
Staturday
)
PlaygroundValue of iota
is its position in the const
block:
const (
US = "United State"
VN = "Vietnam"
Other
Tuesday = iota
)
func main() {
fmt.Println("Tuesday:", Tuesday) // Tuesday: 3
}
PlaygroundIf 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