Created
February 28, 2020 10:21
-
-
Save kirugan/869ad2014818119976e04bfc8d859e6e to your computer and use it in GitHub Desktop.
Interesting implementation of state machine in Golang
This file contains 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
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