This repository demonstrates how to implement and use Stately.ai state machines in Go. It features a simple traffic light state machine example that showcases:
- finite states
- transitions & transition actions
- guarded transitions
- entry, exit, and transition actions
This serves as a starting point for developers looking to integrate Stately.ai state machines into their Go projects. More advanced examples are coming in the future, and contributions are welcome to help expand the functionality and showcase additional state machine/statechart features in Go.
To run this example, follow these steps:
-
Ensure you have Go installed on your system. You can download it from https://golang.org/.
-
Clone this repository
-
Run the example:
go run main.go
The algorithm for transitioning the state machine in main.go
can be summarized in the following steps:
- Check if the current state exists in the state machine definition
- Look for a transition matching the given event type in the current state
- If a guard is specified for the transition:
- Execute the guard function with the provided parameters
- If the guard returns false, return the current state without transitioning
- Determine the next state based on the transition's target
- Collect actions to be executed in the following order:
- Exit actions of the current state
- Transition actions
- Entry actions of the next state
- Return a tuple of the next state and the collected actions to execute.
This algorithm is implemented in the TransitionStateMachine
function.