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"
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)
}
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() {
var i int = num
var j int64 = num
var k float64 = num
var n number = num
fmt.Println(i, j, k, n)
var bigFloat float64 = bigNum
fmt.Printf("%t, %t", bigNum == bigNum+1, bigFloat == bigFloat+1)
}
Playground
iota
identifier can be used in constant declarations to simplify definitions of incrementing numbers:
type ByteSize float64
const (
_ = iota
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 iota
is its position in the const
block:
const (
US = "United State"
VN = "Vietnam"
Other
Tuesday = iota
)
func main() {
fmt.Println("Tuesday:", Tuesday)
}
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)
}
Playground