1. 程式人生 > 其它 >go語言中iota和左移<< 右移<<

go語言中iota和左移<< 右移<<

iota 特殊常量

在go語言中iota比較特殊,是一個被編譯器修改的常量,在每一個const關鍵字出現時被重置為0,然後在下一個const出現之前,每出現一次iota,其所代表的數字就會自動加1

package main

import "fmt"

func main() {
	// 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)
}
a = 0, b = 1, c = 2
d = 0
a1 = 0, b1 = 1, c1 = 2
i = 0, j1 = 1, j2 = 1, j3 = 1, k = 2

左移運算子"<<" 雙目運算子

左移n位就是乘以2的n次方。 其功能把<<左邊的運算數的各二進位全部左移若干位,由<<右邊的數指定移動的位數,高位丟棄,低位補0。

package main

import "fmt"

func main() {
	const (
		a = 1 << iota //a = 1  1乘以2的0次方 1*1
		b = 1 << iota //b = 2  1乘以2的1次方 1*2
		c = 1 << iota //c = 4  1乘以2的2次方 1*4
	)
	fmt.Println("a = ", a, " b = ", b, " c = ", c, "\n")
}
a =  1  b =  2  c =  4

右移運算子">>" 雙目運算子

右移n位就是除以2的n次方。 其功能是把>>左邊的運算數的各二進位全部右移若干位,>>右邊的數指定移動的位數。

package main

import "fmt"

func main() {
	const (
		a = 1 >> iota //a = 1  1除以2的0次方 1/1
		b = 2 >> iota //b = 1  2除以2的1次方 2/2
		c = 4 >> iota //c = 1  4除以2的2次方 4/4
		d = 4 >> iota //d = 0  4除以2的3次方 4/8
	)
	fmt.Println("a = ", a, " b = ", b, " c = ", c, " d = ", d,"\n")
}
a =  1  b =  1  c =  1 d = 0