0

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

type status enum[string] {
    pending = "PENDING"
    active = "ACTIVE"
}
David Alsh
  • 3,997
  • 4
  • 21
  • 37

2 Answers2

4

Something like the following?

Not yet

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

Maxim
  • 1,763
  • 4
  • 14
  • 1
    allow me to provide some of language's author code regarding "enums": https://golang.org/src/net/http/status.go – Victor Dec 22 '18 at 15:23
4
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]
}
blobdon
  • 780
  • 4
  • 10