04 | 常量与iota

2020-03-21  本文已影响0人  刀斧手何在

常量

const Con string = "hello"
const Constr = "world"
func TestCon(t *testing.T){
    //t.Log(getConNum())
    t.Log(Con)
    t.Log(Constr)
    t.Log(reflect.TypeOf(Con))
}
func getConNum() int {
    return 1
}

const Con  = getConNum()
func TestCon(t *testing.T){
    //t.Log(getConNum())
    t.Log(Con)
}
//result : const initializer getConNum() is not a constant

当然下面的代码是可以正常运行的,因为string实际上不是函数,而是关键字

const Con  = string(65)
func TestCon(t *testing.T){
    //t.Log(getConNum())
    t.Log(Con)
}
//result : A
const Conint = 1
func TestCon(t *testing.T){
    var i8 int8 = Conint
    var i64 int64 = Conint
    t.Log(Conint)
    t.Log(reflect.TypeOf(Conint))
    t.Log(i8)
    t.Log(reflect.TypeOf(i8))
    t.Log(i64)
    t.Log(reflect.TypeOf(i64))
}
//result: 1,int,1,int8,1,int64
//Conint = 1.1 => constant 1.1 truncated to integer 
//Conint = 65536 => constant 65536 overflows int8

const (
    a = 1
    b
    c = 1.1
    d
)
func TestCon(t *testing.T){
    t.Log(a,b,c,d)
    t.Log(reflect.TypeOf(a))
    t.Log(reflect.TypeOf(b))
    t.Log(reflect.TypeOf(c))
    t.Log(reflect.TypeOf(d))
}
//result 1,1,1.1,1.1

除了第一个外,其它的常量右边的初始化表达式都可以省略,如果省略初始化表达式则表示使用前面常量的初始化表达式,对应的常量类型也是一样的

iota

在常量声明中,预声明的标识符 iota表示连续的无类型整数。它的值为常量定义所在行的索引,从0开始计数。所以 也叫做常量计数器。

const (
    c0 = iota // c0 == 0 iota = 0
    c1 = -1 // c1 == -1 iota = 1(未使用)
    c2,c3 = iota ,iota+2// c2 == 2 c3 == 2+2 iota = 2
    c5 = iota // c5 == 4
)
const c6  = iota //iota = 0
func TestCon(t *testing.T){
    t.Log(c0,c1,c2,c3,c5,c6)
}
func TestCon(t *testing.T){
    t.Log(iota)
}
//result : undefined: iota
const (
    Sunday = iota
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Partyday
)
func TestCon(t *testing.T){
    t.Log(Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Partyday)
}
const (
    Readable = 1 << iota
    Writeable
    Executable
)
func TestCon(t *testing.T){
    t.Log(Readable,Writeable,Executable)
}
上一篇 下一篇

猜你喜欢

热点阅读