1
0
Fork 0
pr3-sose2026-fork/go/01-basics/10-enums.go

51 lines
1.3 KiB
Go

package main
import "fmt"
// Go does not have a native enum type, but you can achieve similar functionality using constants and iota.
type ServerState int
// iota is a special identifier that is reset to 0 whenever the word const appears in the source and
// increments by one after each const specification. It is often used to create enumerated constants.
const (
StateIdle ServerState = iota
StateConnected
StateError
StateRetrying
)
// We can use a map to associate the ServerState values with their string representations.
var stateName = map[ServerState]string{
StateIdle: "idle",
StateConnected: "connected",
StateError: "error",
StateRetrying: "retrying",
}
// By implementing the Stringer interface, we can define how our ServerState values are printed.
func (ss ServerState) String() string {
return stateName[ss]
}
func main() {
ns := transition(StateIdle)
fmt.Println(ns)
ns2 := transition(ns)
fmt.Println(ns2)
}
func transition(s ServerState) ServerState {
// A simple state machine that transitions between states based on the current state.
switch s {
case StateIdle:
return StateConnected
case StateConnected, StateRetrying:
return StateIdle
case StateError:
return StateError
default:
panic(fmt.Errorf("unknown state: %s", s))
}
}