How to use enum in GoLang
In this article, you are going to learn about how to use enum in the Go language.
Enum refers to the term as a special data type that contains a set of predefined constants. It is also known as an enumerator. Enums are used widely and very powerful but like some other programming languages, the Go language does not support enum directly. But you may implement it in the Go language and to do so you need to use iota which is a predeclared identifier.
In the Go language, Iota is nothing but an identifier that is used with constant and incrementing numbers automatically. Basically, it represents an integer constant that starts from zero. To implement enum in the Go language, iota is used. Let’s see an example of it to understand things more clearly in below:
package main
import "fmt"
type Profession int
const (
Doctor Profession = iota
Developer
Teacher
Entrepreneur
)
func main() {
var myProfession Profession
myProfession = Developer
if myProfession == Developer {
fmt.Println("My Profession is Developer", myProfession)
}
}
//Output: My Profession is Developer 1
Here, we have taken profession enum with possible values of a doctor, developer, teacher, entrepreneur. We have already known that iota is represented a numeric constant value that starts from zero and we can see in our program that the developer is at position number 1. That means our program is successfully running. Let’s see another example of implementing enum with the help of iota in the Go language.
package main
import "fmt"
type Gender int
const (
Male Gender = iota
Female
)
func main() {
var myGender Gender
myGender = 0
if myGender == 0 {
fmt.Println("My Gender is Male")
}
}
//Output: My Gender is Male
Here, we have checked if gender is male or female, and if gender value is 0 that will refer to as male, and if 1 it will refer to as female. You can see it in the output and this is the approach you may follow to implement enum in the Go language.