https://github.com/things-go/fsm
Finite State Machine
https://github.com/things-go/fsm
Last synced: 5 months ago
JSON representation
Finite State Machine
- Host: GitHub
- URL: https://github.com/things-go/fsm
- Owner: things-go
- License: mit
- Created: 2022-08-12T07:13:37.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2024-05-08T05:38:28.000Z (about 2 years ago)
- Last Synced: 2024-06-20T08:14:49.056Z (almost 2 years ago)
- Language: Go
- Homepage:
- Size: 96.7 KB
- Stars: 2
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# fsm
Finite State Machine
[](https://pkg.go.dev/github.com/things-go/fsm?tab=doc)
[](https://codecov.io/gh/things-go/fsm)
[](https://github.com/things-go/fsm/actions/workflows/ci.yml)
[](https://goreportcard.com/report/github.com/things-go/fsm)
[](https://raw.githubusercontent.com/things-go/fsm/main/LICENSE)
[](https://github.com/things-go/fsm/tags)
## Features
## Usage
### Installation
Use go get.
```bash
go get github.com/things-go/fsm
```
Then import the package into your own code.
```bash
import "github.com/things-go/fsm"
```
### Example
[embedmd]:# (examples/generic.go go)
```go
package main
import (
"fmt"
"github.com/things-go/fsm"
)
type MyEvent int
const (
Close MyEvent = 1
Open MyEvent = 2
)
func (c MyEvent) String() string {
switch c {
case 1:
return "close"
case 2:
return "open"
default:
return "none"
}
}
type MyState int
func (c MyState) String() string {
switch c {
case 1:
return "closed"
case 2:
return "opened"
default:
return "none"
}
}
const (
IsClosed MyState = 1
IsOpen MyState = 2
)
func main() {
f := fsm.NewSafeFsm[MyEvent, MyState](
IsClosed,
fsm.NewTransition([]fsm.Transform[MyEvent, MyState]{
{Event: Open, Src: []MyState{IsClosed}, Dst: IsOpen},
{Event: Close, Src: []MyState{IsOpen}, Dst: IsClosed},
}),
)
fmt.Println(f.Current())
err := f.Trigger(Open)
if err != nil {
fmt.Println(err)
}
fmt.Println(f.Current())
err = f.Trigger(Close)
if err != nil {
fmt.Println(err)
}
fmt.Println(f.Current())
// Output:
// closed
// opened
// closed
fmt.Println(fsm.VisualizeGraphviz[MyEvent, MyState](f))
// digraph fsm {
// "closed" -> "opened" [ label = "open" ];
// "opened" -> "closed" [ label = "close" ];
//
// "closed";
// "opened";
// }
}
```
## License
This project is under MIT License. See the [LICENSE](LICENSE) file for the full license text.