Skip to content

Instantly share code, notes, and snippets.

@ciniglio
Created November 29, 2012 16:13
Show Gist options
  • Save ciniglio/4170068 to your computer and use it in GitHub Desktop.
Save ciniglio/4170068 to your computer and use it in GitHub Desktop.
Internal Channels Pattern
func main() {
t := NewThing(0)
var r int
for i := 0; i < 10; i++ {
r = t.inc()
}
}
type Thing struct {
state int
internal chan message
}
type message struct {
f func(int) int
ret chan int
}
func NewThing(i int) Thing{
t := new(Thing)
t.state = i
t.internal = make(chan message)
go t.run()
return t
}
func (t Thing) run() {
for m := range t.internal {
t.i = m.f(t.i)
m.ret <- t.i
}
}
func (t Thing) Inc() int{
m := new(message)
m.f = func(i int){ return i + 1 }
m.ret = make(chan int)
t.internal <- m
return <- m.ret
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment