go语言中iota的一个例子

package main
import (
    "fmt"
)
type BitFlag int
const (
    // iota为0,1左移0位 = 1
    Active BitFlag = 1 << iota
    // Send <=> Active <=> 1 << iota,此时iota为1,1左移1位 = 2
    Send
    // Receive <=> Send <=> 1 << iota,此时iota为2,1左移2位 = 4
    Receive
)
func main() {
    fmt.Println(Active, Send, Receive)
}

iota是在编译的时候,编译器根据代码中iota与const关键字的位置动态替换的。code

package main

import (
    "fmt"
)

const (
    //e=0,f=0,g=0
    e, f, g = iota, iota, iota
)

func main() {
    fmt.Println(e, f, g)
}

能够将iota理解为const语句的行索引索引

package main

import (
    "fmt"
)

func main() {
    fmt.Println(iota)
}

编译错误:undefined: iota.编译器


iota是预先声明的标识符,可是只能做用在const常量声明里。
我怎么以为iota这东西是go的私生子,只能被关在某个地方,不一样于true/false等这些兄弟,不能访问它。it

相关文章
相关标签/搜索