go

In Go, there's no native `enum` type like in some other languages, but we can create similar behavior using const blocks with typed constants.
Enums in Go are typically implemented by defining a series of constants of a specific type.
These constants are grouped together to represent a set of related values, often with an underlying integer type.

Practical Go Lessons

Example: Simple Enum Using iota

The iota identifier is a built-in counter that starts at 0 and increments by 1 for each item in a const block. This is commonly used to create enums.

package main
 
import "fmt"
 
// Define an enum type using iota
type Day int
 
const (
    Sunday Day = iota  // 0
    Monday             // 1
    Tuesday            // 2
    Wednesday          // 3
    Thursday           // 4
    Friday             // 5
    Saturday           // 6
)
 
func main() {
    // Print each day
    fmt.Println(Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)
 
    // Example usage
    today := Wednesday
    fmt.Println("Today is:", today)
}

Output:

0 1 2 3 4 5 6
Today is: 3

Using Enums with String Method

To make enums more user-friendly, especially for debugging, you can add a String method to give each constant a name when printed.

package main
 
import "fmt"
 
type Day int
 
const (
    Sunday Day = iota
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
)
 
// Add a String method to format enum as string
func (d Day) String() string {
    switch d {
    case Sunday:
        return "Sunday"
    case Monday:
        return "Monday"
    case Tuesday:
        return "Tuesday"
    case Wednesday:
        return "Wednesday"
    case Thursday:
        return "Thursday"
    case Friday:
        return "Friday"
    case Saturday:
        return "Saturday"
    default:
        return "Unknown"
    }
}
 
func main() {
    fmt.Println("Today is:", Tuesday) // Outputs: Today is: Tuesday
}

With the String method, printing Tuesday now gives "Today is: Tuesday" instead of "Today is: 2".

Enum Values with Non-Integer Types

While iota commonly increments integers, you can also create enums with non-integer types by assigning specific values.

type LogLevel string
 
const (
    Info    LogLevel = "INFO"
    Warning LogLevel = "WARNING"
    Error   LogLevel = "ERROR"
)
 
func logMessage(level LogLevel, message string) {
    fmt.Printf("[%s] %s\n", level, message)
}
 
func main() {
    logMessage(Info, "Application started")        // Outputs: [INFO] Application started
    logMessage(Warning, "Low disk space")          // Outputs: [WARNING] Low disk space
    logMessage(Error, "Failed to load configuration") // Outputs: [ERROR] Failed to load configuration
}