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
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值