首页 > 编程语言 > go语言中iota和左移右移的使用说明
2021
06-19

go语言中iota和左移右移的使用说明

在go语言中iota比较特殊,是一个被编译器修改的常量,在每一个const关键字出现时被重置为0,然后在下一个const出现之前,每出现一次iota,其所代表的数字就会自动加1

左移运算符"<<“是双目运算符

左移n位就是乘以2的n次方。 其功能把”<<“左边的运算数的各二进位全部左移若干位,由”<<"右边的数指定移动的位数,高位丢弃,低位补0。

右移运算符">>“是双目运算符

右移n位就是除以2的n次方。 其功能是把”>>“左边的运算数的各二进位全部右移若干位,”>>"右边的数指定移动的位数。

package iota
import "fmt"
func Test()  {
	const(
		c1 = iota  //c1=0
		c2 = iota  //c2=1
		c3 = iota  //c3=2
	)
	fmt.Println("c1 = ",c1," c2 = ",c2," c3 = ",c3,"\n")
	const(
		a = 1 << iota //a = 1
		b = 1 << iota //b = 2
		c = 1 << iota //c = 4
	)
	fmt.Println("a = ",a," b = ",b," c = ",c,"\n")
	const(
		v1 = iota //v1 = 0
		v2        //v2 = 1
		v3        //v3 = 2
	)
	fmt.Println("v1 = ",v1," v2 = ",v2," v3 = ",v3,"\n")
	const(
		x = 1 <<iota //x = 1
		y			  //y = 2
		z             //z = 4
	)
	fmt.Println("x = ",x," y = ",y," z = ",z)
}

代码执行结果和上面注释相同:

这里写图片描述

补充:go语言 iota枚举类型

一.概述

go语言中的枚举,和java中一样,都是从0开始

二.说明

// 1.iota常量自动生成器,每隔一行,自动累加1
// 2.iota给常量赋值用
const (
a = iota //0
b = iota //1
c = iota //2
)
fmt.Printf("a = %d, b = %d, c = %d\n", a, b, c)
 
 
// 3.iota遇到const,重置为0
const d = iota
fmt.Printf("d = %d\n", d)
 
 
// 4 可以只写一个iota
const (
a1 = iota //0
b1        //1
c1        //2
)
fmt.Printf("a1 = %d, b1 = %d, c1 = %d\n", a1, b1, c1)
 
 
// 5 如果是同一行,值都一样
const (
i          = iota
j1, j2, j3 = iota, iota, iota
k          = iota
)
 
fmt.Printf("i = %d, j1 = %d, j2 = %d, j3 = %d, k = %d\n", i, j1, j2, j3, k)

二.代码运行结果

以上为个人经验,希望能给大家一个参考,也希望大家多多支持自学编程网。如有错误或未考虑完全的地方,望不吝赐教。

编程技巧