Go語言建立列舉類程式
列舉將相關的常量組合成單個型別。列舉是一個強大的特性,具有許多應用。然而,與大多數其他程式語言相比,它們在Go語言中的實現方式大相徑庭。在本文中,我們將瞭解如何使用預宣告的可標識iota來在Go語言中實現列舉。
IOTA − Iota是一個用於常量的識別符號,可以使基於自動遞增數字的常量定義更簡單。“iota”關鍵字代表一個從零開始的整數常量。
實現Iota
package main
import "fmt"
const (
c0 = iota + 1
c1
c2
)
func main() {
fmt.Println(c0, c1, c2) // Print : 1 2 3
}
輸出
1 2 3
建立星期幾的列舉
演算法
步驟1 − 匯入fmt包,允許我們在螢幕上列印任何內容。
步驟2 − 建立一個新的資料型別Weekday來儲存星期幾的整型。
步驟3 − 從索引1開始,為每個星期幾宣告相關的常量。
步驟4 − 建立一個函式,根據提供的整數值獲取星期幾的字串。
步驟5 − 建立一個函式來獲取列舉的索引。
步驟6 − 呼叫main()函式。
步驟7 − 初始化Weekday型別並存儲一天。
步驟8 − 透過分別呼叫getWeekday()和getIndex()函式列印相應的星期幾和索引。
示例
在下面的示例中,我們正在為星期幾建立列舉。
package main
import "fmt"
type Weekday int
// Declaring related constants for each weekday starting with index 1
const (
Sunday Weekday = iota + 1
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
)
// creating a function to get the weekday as string from the integer values provided
func (w Weekday) getWeekday() string{
return [...]string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday"} [w-1]
}
// creating a function to get the index of the enum
func (w Weekday) getIndex() int {
return int(w)
}
func main() {
var weekday = Sunday
fmt.Println(weekday)
fmt.Println(weekday.getWeekday())
fmt.Println(weekday.getIndex())
}
輸出
1 Sunday 1
建立方向列舉
演算法
步驟1 − 匯入fmt包,允許我們列印任何內容。
步驟2 − 建立一個新的型別Direction來儲存從1到7的方向整型。
步驟3 − 為每個方向宣告常量作為Direction,並使用iota為常量集編制索引。請注意,第一個方向,即北,索引為iota + 1,即1,後續方向將獲得自動遞增的值作為索引。
步驟4 − 現在我們需要為Direction型別建立函式。第一個函式返回方向的字串,我們將其命名為getDirection()。而另一個函式返回列舉索引的整數值,我們將其命名為getIndex()。
步驟5 − 現在呼叫main()函式,這是程式的主入口點,程式從這裡開始執行。
步驟6 − 建立一個新的Direction型別變數,並將其中一個方向作為值儲存到其中。
步驟7 − 現在我們可以透過分別呼叫getDirection()和getIndex()函式列印方向以及對應於該方向的列舉索引。
步驟8 − 使用fmt.Println()函式在螢幕上列印此函式返回的結果。
示例
在下面的示例中,我們正在為方向建立列舉
package main
import "fmt"
// creating a new custom type Direction to store the direction values as integers from 1-4
type Direction int
// Declaring related constants for each direction starting with index 1
const (
North Direction = iota + 1
East
South
West
)
// creating a function to get the directions as string from the integer values provided
func (d Direction) getDirection() string {
return [...]string{"North", "East", "South", "West"}[d-1]
}
func (d Direction) getIndex() int {
return int(d)
}
func main() {
var d Direction = West
fmt.Println(d)
fmt.Println(d.getDirection())
fmt.Println(d.getIndex())
}
輸出
4 West 4
結論
我們已經成功編譯並執行了一個Go語言程式來建立列舉類以及示例。我們建立了各種函式來實現建立列舉類的邏輯。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP