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

相關文章
相關標籤/搜索