golang type enum
To create an enum-like structure in Go (golang), you can use the iota
identifier along with a set of constant values. Here are the steps to create a Go enum:
- Declare a new type: Start by declaring a new type that represents your enum. For example, if you want to create an enum for days of the week, you can declare a type called
Day
as follows:
type Day int
- Define constant values: Next, define a series of constant values for your enum using the
const
keyword. Use theiota
identifier to assign incremental values to each constant. For example, to define the days of the week, you can write:
const (
Sunday Day = iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
)
In this example, Sunday
is assigned 0
, Monday
is assigned 1
, and so on. The iota
identifier automatically increments by 1 for each subsequent constant.
- Use the enum: You can now use the
Day
enum in your code. For example, you can create a variable of typeDay
and assign it a value from the enum:
func main() {
today := Tuesday
fmt.Println(today) // Output: 2
}
In this example, the variable today
is assigned the value Tuesday
from the Day
enum. When you print today
, it will output 2
, as Tuesday
is the third constant in the enum and iota
starts from 0
.
That's it! You have successfully created and used an enum-like structure in Go using the iota
identifier. Enums in Go provide a convenient way to represent a set of related constant values.