Would something like this work for you?
package main
import (
"fmt"
)
type Dispatcher struct {
SayHello func()
SayGoodbye func()
}
func (d *Dispatcher) DispatchCommand(i int) func() {
var f func()
switch i {
case 1:
f = d.SayHello
case 2:
f = d.SayGoodbye
}
return f
}
func main() {
d := Dispatcher{ SayHello: func() { fmt.Println("hello!") }, SayGoodbye: func() { fmt.Println("goodbye!") }}
d.DispatchCommand(1)()
d.DispatchCommand(2)()
}
Output:
hello!
goodbye!
that assignment doesn't seem to workf = d.SayHelloit says "method ... is not an expression, must be called"
from the compiler error you're reporting, it looks like you might have been doing / wanted to do something like this:
/*
Code doesn't compile.
Compiler is complaining about the statements
return d.SayHello
return d.SayGoodbye
in method dispatchCommand
method d.SayHello is not an expression, must be called
method d.SayGoodbye is not an expression, must be called
*/
package main
import (
"fmt"
)
type Dispatcher struct {
SomeField int
}
func (d *Dispatcher) SayHello() {
fmt.Println("hello!")
}
func (d *Dispatcher) SayGoodbye() {
fmt.Println("goodbye!")
}
func (d *Dispatcher) dispatchCommand(cmd int) func() {
switch cmd {
case 1:
return d.SayHello
case 2:
return d.SayGoodbye
}
}
func (d *Dispatcher) someOtherMethod() {
f := d.dispatchCommand(d.SomeField)
f()
}
func main() {
d1 := &Dispatcher{1}
d1.someOtherMethod()
d2 := &Dispatcher{2}
d2.someOtherMethod()
}
if you really want to go that route, you could use reflection.
see my example in:
http://play.golang.org/p/rd-iiSyuBW
as you can see, the reflection approach adds complexity to your code,
so it's not something i would recommend using unless i really have to.
evan chua-yap
--