What is an idiomatic way of representing enums in Go?

In Go, there is no built-in enum type like in some other programming languages. Instead, Go developers typically use a set of constant values to represent enums. Go’s constant values are strongly typed and provide compile-time safety, making them a suitable replacement for traditional enums.

Here’s an idiomatic way to represent enums in Go using constants:

package main

import "fmt"

// Enum constants representing days of the week
const (
    Sunday    = iota // 0
    Monday           // 1
    Tuesday          // 2
    Wednesday        // 3
    Thursday         // 4
    Friday           // 5
    Saturday         // 6
)

func dayName(day int) string {
    // Switch statement to convert the day number to its corresponding name
    switch day {
    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 "Invalid day"
    }
}

func main() {
    today := Tuesday
    fmt.Printf("Today is %s.\n", dayName(today))
}

Output:

Today is Tuesday.

In this example, we use a set of constant values to represent the days of the week. The constant iota is used to generate sequential values starting from 0 for each subsequent constant. By using a switch statement, we can easily convert the day number to its corresponding name.

You can extend this pattern to represent other types of enums or constants. For example, you could represent colors, states, or any other predefined set of values using constants. By doing so, you achieve a simple and idiomatic way to handle enums in Go without the need for custom types or external libraries.

error: Content is protected !!