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

来源:互联网 发布:溥仪受审贵族气质知乎 编辑:程序博客网 时间:2024/06/05 00:35

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

// Demo01 project main.gopackage mainimport "fmt"const (a = 1         // iota = 0b = 1 << iota // iota = 1cde = 2fg             // iota = 6)func main() {fmt.Println(a, b, c, d, e, f, g)}结果为: 1 2 4 8 2 2 2 

// Demo01 project main.gopackage mainimport "fmt"const (a = 1b = 1 << iotacde = 200 >> iotafg)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、<< 为左移,>> 为右移,跟在后面的数值为移动的位数


0 0
原创粉丝点击