iota 特殊常量
在go语言中iota
比较特殊,是一个被编译器修改的常量,在每一个const
关键字出现时被重置为0,然后在下一个const
出现之前,每出现一次iota
,其所代表的数字就会自动加1
package main
import "fmt"
func main() {
// 1.iota常量自动生成器,每隔一行,自动累加1
// 2.iota给常量赋值用
const (
a = iota //0
b = iota //1
c = iota //2
)
fmt.Printf("a = %d, b = %d, c = %d\n", a, b, c)
// 3.iota遇到const,重置为0
const d = iota
fmt.Printf("d = %d\n", d)
// 4 可以只写一个iota
const (
a1 = iota //0
b1 //1
c1 //2
)
fmt.Printf("a1 = %d, b1 = %d, c1 = %d\n", a1, b1, c1)
// 5 如果是同一行,值都一样
const (
i = iota
j1, j2, j3 = iota, iota, iota
k = iota
)
fmt.Printf("i = %d, j1 = %d, j2 = %d, j3 = %d, k = %d\n", i, j1, j2, j3, k)
}
a = 0, b = 1, c = 2
d = 0
a1 = 0, b1 = 1, c1 = 2
i = 0, j1 = 1, j2 = 1, j3 = 1, k = 2
左移运算符"<<" 双目运算符
左移n位就是乘以2的n次方。 其功能把<<
左边的运算数的各二进位全部左移若干位,由<<
右边的数指定移动的位数,高位丢弃,低位补0。
package main
import "fmt"
func main() {
const (
a = 1 << iota //a = 1 1乘以2的0次方 1*1
b = 1 << iota //b = 2 1乘以2的1次方 1*2
c = 1 << iota //c = 4 1乘以2的2次方 1*4
)
fmt.Println("a = ", a, " b = ", b, " c = ", c, "\n")
}
a = 1 b = 2 c = 4
右移运算符">>" 双目运算符
右移n位就是除以2的n次方。 其功能是把>>
左边的运算数的各二进位全部右移若干位,>>
右边的数指定移动的位数。
package main
import "fmt"
func main() {
const (
a = 1 >> iota //a = 1 1除以2的0次方 1/1
b = 2 >> iota //b = 1 2除以2的1次方 2/2
c = 4 >> iota //c = 1 4除以2的2次方 4/4
d = 4 >> iota //d = 0 4除以2的3次方 4/8
)
fmt.Println("a = ", a, " b = ", b, " c = ", c, " d = ", d,"\n")
}
a = 1 b = 1 c = 1 d = 0