Skip to content

Instantly share code, notes, and snippets.

@kirugan
Created February 28, 2020 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirugan/869ad2014818119976e04bfc8d859e6e to your computer and use it in GitHub Desktop.
Save kirugan/869ad2014818119976e04bfc8d859e6e to your computer and use it in GitHub Desktop.
Interesting implementation of state machine in Golang
package main
import "fmt"
type connection struct {
closed bool
usage int
}
type state func(*connection) state
func begin(c *connection) state {
if c.closed {
return end
}
c.usage++
return second
}
func second(c *connection) state {
if c.closed {
return end
} else {
c.usage++
return third
}
}
func third(c *connection) state {
const maxUsage = 10
c.usage++
if c.usage > maxUsage {
return end
}
return third
}
func end(*connection) state {
return nil
}
func main() {
c := &connection{}
state := begin
for {
state = state(c)
fmt.Println(c)
if state == nil {
fmt.Println("breaking the loop")
break
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment