Created
April 2, 2020 18:56
-
-
Save embano1/444ab0ae2dc42518b4a12e27843ccd98 to your computer and use it in GitHub Desktop.
Playing with stateFn and a stupid counter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // inspired by | |
| // https://github.com/golang/go/blob/8d7be1e3c9a98191f8c900087025c5e78b73d962/src/text/template/parse/lex.go#L228 | |
| package main | |
| import ( | |
| "fmt" | |
| "log" | |
| ) | |
| type stateFn func(s *state) stateFn | |
| type state struct { | |
| counter int | |
| initialized bool | |
| } | |
| func addOne(s *state) stateFn { | |
| s.counter++ | |
| return addTwo(s) | |
| } | |
| func addTwo(s *state) stateFn { | |
| s.counter += 2 | |
| return start | |
| } | |
| func start(s *state) stateFn { | |
| if s == nil { | |
| log.Println("state must not be nil") | |
| return nil | |
| } | |
| if !s.initialized { | |
| s.counter = 0 | |
| s.initialized = true | |
| } | |
| // counter will be incremented by 3 (1+2) | |
| if s.counter >= 9 { | |
| return nil | |
| } | |
| return addOne(s) | |
| } | |
| func main() { | |
| obj := &state{} | |
| // var obj *state | |
| for s := start(obj); s != nil; { | |
| fmt.Printf("running, counter is at %d\n", obj.counter) | |
| s = s(obj) | |
| } | |
| fmt.Println(obj.counter) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment