当前位置:   article > 正文

iota和<<左移>>右移的用法

lota运算

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

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

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

例一:

  1. package iota
  2. import "fmt"
  3. func Test() {
  4. const(
  5. c1 = iota //c1=0
  6. c2 = iota //c2=1
  7. c3 = iota //c3=2
  8. )
  9. fmt.Println("c1 = ",c1," c2 = ",c2," c3 = ",c3,"\n")
  10. const(
  11. a = 1 << iota //a = 1
  12. b = 1 << iota //b = 2
  13. c = 1 << iota //c = 4
  14. )
  15. fmt.Println("a = ",a," b = ",b," c = ",c,"\n")
  16. const(
  17. v1 = iota //v1 = 0
  18. v2 //v2 = 1
  19. v3 //v3 = 2
  20. )
  21. fmt.Println("v1 = ",v1," v2 = ",v2," v3 = ",v3,"\n")
  22. const(
  23. x = 1 <<iota //x = 1
  24. y //y = 2
  25. z //z = 4
  26. )
  27. fmt.Println("x = ",x," y = ",y," z = ",z)
  28. }

 

例二:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. const (
  7. a2 = 1 << iota //iota = 0 a2 = 1 X 2的0次方
  8. b2 = 3 << iota //iota = 1 b2 = 3 X 2的1次方
  9. c2 //iota = 2 c2 = 3 X 2的2次方
  10. d2 //iota = 3 d2 = 3 X 2的3次方
  11. e2 = 120 >> iota //iota = 4 e2 = 120 / 2的4次方
  12. f2 //iota = 5 f2 = 120 / 2的5次方
  13. )
  14. fmt.Println(a2, b2, c2, d2, e2, f2)
  15. //1 6 12 24 7 3
  16. }

 

转载于:https://my.oschina.net/haoye/blog/1612097

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/409706
推荐阅读
相关标签
  

闽ICP备14008679号