golang enum type
package main
import (
"fmt"
)
type Status int
const (
Pending Status = iota
InProgress
Completed
Failed
)
func (s Status) String() string {
statusStrings := [...]string{"Pending", "InProgress", "Completed", "Failed"}
if s < Pending || s > Failed {
return "Unknown"
}
return statusStrings[s]
}
func main() {
var taskStatus Status = Completed
fmt.Println("Task status:", taskStatus.String())
}
Explanation:
Package Declaration: The
main
package is declared, which is the entry point of execution for Go programs.Imports: The
fmt
package is imported for handling input/output operations.Enum Definition: A new type
Status
is declared using theint
underlying type.Constants: The
const
block defines different statuses (Pending
,InProgress
,Completed
,Failed
) using theiota
enumerator to auto-increment their values (0, 1, 2, 3).Stringer Method: A
String()
method is defined for theStatus
type to return a string representation of the status using an array of corresponding status strings.Main Function: Inside the
main
function, a variabletaskStatus
of typeStatus
is declared and initialized with theCompleted
status.Println: Finally, the string representation of the
taskStatus
is printed to the console usingfmt.Println
.