go - how to compare funcs in golang -
i'm attempting write test package , failing @ comparing funcs. here's i'm doing.
package main import ( "fmt" "reflect" ) type handlerfunc func(cmd interface{}) type bus struct { handlers map[reflect.type]handlerfunc } func (bus *bus) registerhandler(cmd interface{}, handler handlerfunc) { bus.handlers[reflect.typeof(cmd)] = handler } func (bus *bus) gethandler(cmd interface{}) handlerfunc { t := reflect.typeof(cmd) kind, handler := range bus.handlers { if t == kind { return handler } } return nil } func new() *bus { return &bus{ handlers: make(map[reflect.type]handlerfunc), } } type registerusercommand struct {} func main() { bus := new() handler := func (cmd interface{}) {} bus.registerhandler(®isterusercommand{}, handler) retrieved := bus.gethandler(®isterusercommand{}) if retrieved != handler { fmt.println("not same!") return } fmt.println("same!") }
comparing retrieved
handler
causes following error
invalid operation: (func(interface {}))(retrieved) != handler (func can compared nil)
how can test function i'm retrieving same 1 added previously?
given can't compare functions, can write test in different way. can make handler
set boolean value in test , check you've got right function calling , seeing if boolean changes.
here's example:
func main() { bus := new() called := false handler := func (cmd interface{}) { called = true } bus.registerhandler(®isterusercommand{}, handler) bus.gethandler(®isterusercommand{})(nil) if called { fmt.println("we got right handler!") return } fmt.println("we didn't right handler") }
Comments
Post a Comment