golang之iota

golang之iota,第1张

iota是一个常量计数器,只能在常量的表达式中使用,iota可理解为const语句块中的行索引

在每一个const关键字出现时被重置为0,然后在下一个const出现之前,每出现一次常量,其所代表的数字会自动增加1(使用_跳过某些值,还是会+1)。

1、iota声明的常量默认会自增1;

const (
	one = iota
	two
	three
	four
	five
)
func main() {
	fmt.Println(one)
	fmt.Println(two)
	fmt.Println(three)
	fmt.Println(four)
	fmt.Println(five)
}


output:
0
1
2
3
4
const (
	one = iota
	two
	three = 10		// 独立值
	four = 11		// 独立值
	five = iota		// 恢复计数
	six
	seven
)
func main() {
	fmt.Println(one)
	fmt.Println(two)
	fmt.Println(three)
	fmt.Println(four)
	fmt.Println(five)
	fmt.Println(six)
	fmt.Println(seven)
}

output:
0
1
10
11
4
5
6

2、支持移位运算

const (
	one = 1 << iota
	two
	three
	four
	five  
	six
	seven
)

func main() {
	fmt.Println(one)
	fmt.Println(two)
	fmt.Println(three)
	fmt.Println(four)
	fmt.Println(five)
	fmt.Println(six)
	fmt.Println(seven)
}

output:
1
2
4
8
16
32
64

3、定义数量级

const (
	//_   = iota
	one = 1 << (10 * iota)
	two
	three
	four
	five
	six
	seven
)

func main() {
	fmt.Println(one)
	fmt.Println(two)
	fmt.Println(three)
	fmt.Println(four)
	fmt.Println(five)
	fmt.Println(six)
	fmt.Println(seven)
}

output:
1
1024
1048576
1073741824
1099511627776
1125899906842624
1152921504606846976

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/990034.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存