7

is there a simple implementation of enums in golang? Something like the following?

type status enum[string] {
    pending = "PENDING"
    active = "ACTIVE"
}
1

2 Answers 2

22
const (
    statusPending = "PENDING"
    statusActive  = "ACTIVE"
)

Or, application of the example at Ultimate Visual Guide to Go Enums

// Declare a new type named status which will unify our enum values
// It has an underlying type of unsigned integer (uint).
type status int

// Declare typed constants each with type of status
const (
    pending status = iota
    active
)

// String returns the string value of the status
func (s status) String() string {
    strings := [...]string{"PENDING", "ACTIVE"}

    // prevent panicking in case of status is out-of-range
    if s < pending || s > active {
        return "Unknown"
    }

    return strings[s]
}
Sign up to request clarification or add additional context in comments.

2 Comments

Duplicating the underlying string values here. Kind of a bummer
@JohnAllen yeah, that's what I'm looking to avoid as well.
6

Something like the following?

Not yet

Read here What is an idiomatic way of representing enums in Go?

1 Comment

allow me to provide some of language's author code regarding "enums": golang.org/src/net/http/status.go

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.