Enums (enumerated types) are sum types that have a fixed number of possible values, each with a distinct name. Golang enums are not a language specific feature but we can implement them using existing language idioms.
package main
import "fmt"
type PlayerState int
const (
Idle PlayerState = iota
Walking
Running
Jumping
)
var stateName = map[PlayerState]string{
Idle: "idle",
Walking: "Walking",
Running: "running",
Jumping: "jumping",
}
// implement fmt.Stringer interface
func (ps PlayerState) String() string {
return stateName[ps]
}
func transition(ps PlayerState) PlayerState {
switch ps {
case Idle:
return Walking
case Walking, Running:
return Jumping
default:
panic(fmt.Errorf("unknown state: %s", ps))
}
}
func main() {
ns := transition(Idle)
fmt.Println(ns)
ns2 := transition(ns)
fmt.Println(ns2)
ns3 := transition(ns2)
fmt.Println(ns3)
}
enums.go Copy
The Stringer interface
The fmt.Stringer interface dictates how the fmt print commands will format the output when the item implementing the interface is passed as an argument to that print command:
package main
import "fmt"
type Person struct {
name string
age int
}
func (p Person) String() string {
return fmt.Sprintf("a person named %s age %d years old", p.name, p.age)
}
func main() {
person := Person{name: "Jamie", age: 10}
person2 := Person{name: "Henry", age: 12}
fmt.Println("We came across", person)
fmt.Println("Bro said he knows", person2)
}
fmt-stringer.go Copy
The stringer interface’s String method must be on the normal receiver type instead of the pointer receiver type of the struct.