Fork me on GitHub
打赏

Go语言_iota用法

一、介绍

iota,特殊常量,可以认为是一个可以被编译器修改的常量。

在每一个const关键字出现时,被重置为0,然后再下一个const出现之前,每出现一次iota,其所代表的数字会自动增加1。

iota 可以被用作枚举值:

package main
import "fmt"
func main() {
    const (
        a = iota   //0
        b = iota   //1
        c = iota   //2
    )
    fmt.Println(a,b,c)
}

第一个 iota 等于 0,每当 iota 在新的一行被使用时,它的值都会自动加 1;所以 a=0, b=1, c=2 可以简写为如下形式:

    const (
        a = iota   
        b        
        c 
    )

 

二、用法

1,作为累加器

package main

import "fmt"

func main() {
    const (
            a = iota   //0
            b          //1
            c          //2
            d = "ha"   //独立值,iota += 1
            e          //"ha"   iota += 1
            f = 100    //iota +=1
            g          //100  iota +=1
            h = iota   //7,恢复计数
            i          //8
    )
    fmt.Println(a,b,c,d,e,f,g,h,i)
}

 

2,移位运算

package main
import "fmt"
const (
    i=1<<iota  //1<<0  二进制 0000 0001
    j=3<<iota  //3<<1  二进制 0000 0110
    k       //3<<2  二进制 0000 1100
    l       //3<<3  二进制 0001 1000
)

func main() {
    fmt.Println("i=",i)
    fmt.Println("j=",j)
    fmt.Println("k=",k)
    fmt.Println("l=",l)
}

简单表述:

  • i=1:左移0位不变,所以仍为1;
  • j=3:左移一位从0000 0011变为0000 0110,所以为6;
  • k=3:左移两位从0000 0011变为0000 1100,所以为12;
  • l=3:左移三位从0000 0011变为0001 1000,所以为24。

 

三、参考资料

iota: Golang 中优雅的常量

iota:Elegant Constants in Golang

 

posted @ 2018-07-26 18:01  Zoctopus_Zhang  阅读(2001)  评论(0编辑  收藏  举报
// function btn_donateClick() { var DivPopup = document.getElementById('Div_popup'); var DivMasklayer = document.getElementById('div_masklayer'); DivMasklayer.style.display = 'block'; DivPopup.style.display = 'block'; var h = Div_popup.clientHeight; with (Div_popup.style) { marginTop = -h / 2 + 'px'; } } function MasklayerClick() { var masklayer = document.getElementById('div_masklayer'); var divImg = document.getElementById("Div_popup"); masklayer.style.display = "none"; divImg.style.display = "none"; } setTimeout( function () { document.getElementById('div_masklayer').onclick = MasklayerClick; document.getElementById('btn_donate').onclick = btn_donateClick; var a_gzw = document.getElementById("guanzhuwo"); a_gzw.href = "javascript:void(0);"; $("#guanzhuwo").attr("onclick","follow('33513f9f-ba13-e011-ac81-842b2b196315');"); }, 900);