18 ms·
Personally I'd model a state machine in Go as type State int type Transition int func (s State) Next(t Transition) (State, error) { /* doubl
by JulianMorrison 14y ago
Personally I'd model a state machine in Go as
type State int
type Transition int
func (s State) Next(t Transition) (State, error) {
/* doubly nested switch goes here */
}
- zemo 14y agotype state struct { // add any fields you need to persist here } type transition func(*state) transition same as in Lexical Scanning in Go (http://www.youtube.com/watch?v=HxaD_trXwRE http://www.youtube.com/watch?v=HxaD_trXwRE)
- JulianMorrison 14y agoThe reason I didn't do that is a function from state to state is pure in a functional programming sense as well as being simple, free from virtual dispatch and indirection, and thus fast. It's also easy to harness for testing, because it's side effect free and stateless. If you wanted to extend it to perform actions on state change, I'd extend the return values to (State, Action, error) where Action is "type Action int" as well, and use the Action in another switch. Thus you are free to pick which actions you care about, and test the actions separately from the state engine.