package main
import (
_ "fmt"
)
//常量值必须是编译可以确定的数字/数据布尔值
const x, y int = 1,2//多常量初始化
const s = "HelloWorld"//类型自判断
const(//常量组
a,b = 10,100
c bool = false
)
//常量值还可以是len、cap、unsafe.sizeof等编译期可以确定的值
const (
o = "abc"
d = len(o)
//c = unsafe.Sizeof(b)
)
//如果常量类型⾜足以存储初始化值,那么不会引发溢出错误。
const(
p byte = 100//int to byte
//b int = 1e20 //float to int,overflows
)
//枚举
//关键字iota定义常量从0开始枚举增加
const (
Sunday = iota //0
Monday //1
Tuesday //2
Wednesday //3
Thursday
Friday
Saturday
)
const(
_ = iota //0
KB int64 = 1 << (10* iota )//IOTA = 1
MB //2
GB
TB
)
//提供多个iota让它各自增长
const (
A,B = iota,iota<<10 //0,0<<10
C,D //1,1<<10
)
//iota被打断,需要显示恢复
const(
Q = iota //0
W //1
E = "C" //c
R //与上一行相同
T = iota //4,显示恢复 注意包含了CD两行的计算
Y //5
)
//可以通过自定义类型来实现枚举类型限制
type Color int
const (
Black Color = iota
Rad
Blue
)
func test(c Color) {
}
func main() {
c :=Black
test(c)
//x:=1
//test(x)//cannot use x (type int) as type Color in argument to test
test(1)//常量会被编译器自动转换
}