栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

golang之iota

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

golang之iota

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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/903120.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号