如何在Go語言中使用iota?


Go語言中的**iota**用於表示常量遞增序列。在常量中重複使用它時,其值在每次指定後都會遞增。在本文中,我們將探討在Go語言中使用**iota**的不同方法。

讓我們首先考慮一個非常基本的例子,我們將宣告多個常量並使用iota。

示例1

請考慮以下程式碼

package main
import (
   "fmt"
)
const (
   first = iota
   second = iota
   third = iota
)
func main() {
   fmt.Println(first, second, third)
}

輸出

如果我們執行命令**go run main.go**,那麼我們將在終端中得到以下輸出。

0 1 2

我們也可以省略上述示例中**iota**關鍵字的重複使用。請考慮以下程式碼。

示例2

package main
import (
   "fmt"
)
const (
   first = iota
   second
   third
)
func main() {
   fmt.Println(first, second, third)
}

輸出

如果我們執行命令**go run main.go**,那麼我們將在終端中得到以下輸出。

0 1 2

**iota**不需要從預設值開始;我們也可以從1開始。

示例3

請考慮以下程式碼

package main
import (
   "fmt"
)
const (
   first = iota + 1
   second
   third
)
func main() {
   fmt.Println(first, second, third)
}

輸出

如果我們執行命令**go run main.go**,那麼我們將在終端中得到以下輸出。

1 2 3

我們也可以在使用**iota**時跳過值。

示例4

請考慮以下程式碼。

package main
import (
   "fmt"
)
const (
   first = iota + 1
   second
   _
   fourth
)
func main() {
   fmt.Println(first, second, fourth)
}

輸出

如果我們執行命令**go run main.go**,那麼我們將在終端中得到以下輸出。

1 2 4

更新於:2022年2月22日

5K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告