A simple finite state machine (FSM) demonstrating the basics of Statekit.
- Basic state transitions
- Entry actions
- Context management
- Event handling
┌─────────┐
│ green │◄──────────────┐
└────┬────┘ │
│ TIMER │
▼ │
┌─────────┐ │
│ yellow │ │
└────┬────┘ │
│ TIMER │ TIMER (incrementCycle)
▼ │
┌─────────┐ │
│ red │───────────────┘
└─────────┘
package main
import (
"fmt"
trafficlight "go.klarlabs.de/statekit/examples/traffic_light"
"go.klarlabs.de/statekit"
)
func main() {
machine, _ := trafficlight.NewTrafficLight()
interp := statekit.NewInterpreter(machine)
interp.Start()
fmt.Println(interp.State().Value) // "green"
interp.Send(statekit.Event{Type: "TIMER"})
fmt.Println(interp.State().Value) // "yellow"
interp.Send(statekit.Event{Type: "TIMER"})
fmt.Println(interp.State().Value) // "red"
interp.Send(statekit.Event{Type: "TIMER"})
fmt.Println(interp.State().Value) // "green"
ctx := interp.State().Context
fmt.Println(ctx.CycleCount) // 1
}go test -v ./examples/traffic_light/...The Context struct tracks state across transitions:
type Context struct {
CycleCount int // Tracks complete cycles
Log []string // Entry action logs
}Each state logs its entry:
WithAction("logGreen", func(ctx *Context, e statekit.Event) {
ctx.Log = append(ctx.Log, "Entered GREEN")
})The incrementCycle action fires when transitioning from red back to green:
State(StateRed).
On(EventTimer).Target(StateGreen).Do("incrementCycle")