https://github.com/qustavo/go-fsm-example
An example FSM implementation in Go
https://github.com/qustavo/go-fsm-example
Last synced: 2 months ago
JSON representation
An example FSM implementation in Go
- Host: GitHub
- URL: https://github.com/qustavo/go-fsm-example
- Owner: qustavo
- License: bsd-2-clause
- Created: 2014-08-16T17:54:12.000Z (over 10 years ago)
- Default Branch: master
- Last Pushed: 2022-01-04T11:41:13.000Z (over 3 years ago)
- Last Synced: 2025-02-15T06:16:19.717Z (2 months ago)
- Language: Go
- Size: 2.93 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
go-fsm-example
==============An example FSM implementation in Go using State functions (or what I understood from [Lexical Scanning in Go](https://talks.golang.org/2011/lex.slide#16))
The idea is simple, each state function returns the next state.
```go
// stateFn represents the state of the machine
// as a function that returns the next state.
type stateFn func(*fsm) stateFn
```Then each state is defined as a function that receives a `*fsm` and return a `stateFn`
```go
func idleState(f *fsm) stateFn {
f.code = ""
fmt.Printf("Enter code: ")
return readState
}
```
In this example I'm creating a fsm that verify some secret code.To represent the `done` state a `stateFn` must return `nil` and the machine stops, the main loop looks like:
```go
func (self *fsm) run() {
self.reader = bufio.NewReader(os.Stdin)
for s := idleState; s != nil; {
s = s(self)
}
}
```And that's it.