Go 语言常量定义与<<(左移)、>>(右移)和ioto的使用

xiaoxiao2021-02-28  66

我们都知道 << 表示为左移,>> 为右移,比如 << 1 为左移一位, >> 1 为 右移1位,现在看看Go语言常量定义const中用<<、>> 中的使用,先看示例:

// Demo01 project main.go package main import "fmt" const ( a = 1 // iota = 0 b = 1 << iota // iota = 1 c d e = 2 f g // iota = 6 ) func main() { fmt.Println(a, b, c, d, e, f, g) } 结果为: 1 2 4 8 2 2 2   // Demo01 project main.go package main import "fmt" const ( a = 1 b = 1 << iota c d e = 200 >> iota f g ) func main() { fmt.Println(a, b, c, d, e, f, g) } 输出结果为:1 2 4 8 12 6 3   到这里应该可以看出个所以然了,首先我们只 iota 为在遇到下一个 const之前为从0开始每次加1,其次为在const因式分解式定义中,未定义的值为前一个最近赋值的值,比如 c的值为 1 << iota,由于到c是 iota的值已经为2,所以 1<< 2为4(二进制:1<<2 = 100,换为十进制 2^3=8)。

总结一下:

1、在const因式分解式定义中,未定义的值为前一个最近赋值的值。

2、在定义const的常量时,iota的值为0,在之后没有遇到const的关键字时,每一个新行自增1

3、<< 为左移,>> 为右移,跟在后面的数值为移动的位数

转载请注明原文地址: https://www.6miu.com/read-74158.html

最新回复(0)