I'm modeling the state machine implementation outlined in this talk by Rob Pike https://www.youtube.com/watch?v=HxaD_trXwRE&t=1830s and I'm not able to get it to compile. I've provided a small sample that fails.
The call: m := New(foo) fails with
./main.go:31:11: undefined: foo
I've tried
m := New(M.foo)
m := New(foo(*M))
I don't know the proper syntax for this.
package main
type StateFunc func(*M) StateFunc
type M struct {
start StateFunc
}
func New(start StateFunc) *M {
return &M{
start: start,
}
}
func (m *M) foo() StateFunc {
return nil
}
func (m *M) Start() {
go m.run()
}
func (m *M) run() {
state := m.start
for state != nil {
state = state(m)
}
}
func main() {
m := New(foo)
}
I would expect it to compile but I don't know the proper syntax to make this work.
the method (m *M) foo()
doesn't match the signature of type StateFunc func(*M) StateFunc
foo
is a method, it has a receiver *M
, you can't use it without the receiver.
my suggestion is to modify foo
:
func foo(*M) StateFunc {
return nil
}