如何比较golang中的funcs

如何比较golang中的funcs,go,Go,我正在尝试为我的包编写测试,但无法比较funcs。这就是我正在做的事情 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 Hand

我正在尝试为我的包编写测试,但无法比较funcs。这就是我正在做的事情

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)

    for 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(&RegisterUserCommand{}, handler)

    retrieved := bus.GetHandler(&RegisterUserCommand{})

    if retrieved != handler {
        fmt.Println("Not the same!")
        return
    }

    fmt.Println("Same!")
}
将检索到的
处理程序进行比较会导致以下错误

invalid operation: (func(interface {}))(retrieved) != handler (func can only be compared to nil)

如何正确地测试我正在检索的函数与前面添加的函数相同?

如果无法比较函数,可以用不同的方式编写测试。您可以让
handler
在测试中设置一个布尔值,并通过调用它并查看布尔值是否发生变化来检查您是否使用了正确的函数

下面是一个例子:

func main() {
    bus := New()
    called := false
    handler := func (cmd interface{}) { called = true }

    bus.RegisterHandler(&RegisterUserCommand{}, handler)
    bus.GetHandler(&RegisterUserCommand{})(nil)

    if called {
        fmt.Println("We got the right handler!")
        return
    }

    fmt.Println("We didn't get the right handler")
}

由于不能比较函数,所以可以用不同的方式编写测试。您可以让
handler
在测试中设置一个布尔值,并通过调用它并查看布尔值是否发生变化来检查您是否使用了正确的函数

下面是一个例子:

func main() {
    bus := New()
    called := false
    handler := func (cmd interface{}) { called = true }

    bus.RegisterHandler(&RegisterUserCommand{}, handler)
    bus.GetHandler(&RegisterUserCommand{})(nil)

    if called {
        fmt.Println("We got the right handler!")
        return
    }

    fmt.Println("We didn't get the right handler")
}

这并不是对您实际问题的回答,但是为什么要在
GetHandler
中迭代类型到处理程序的映射呢?您可以返回
bus.handlers[t]
,对于未定义的处理程序,这将返回
nil
。@mkb因为我是哑巴,这可能不是您实际问题的答案,但为什么您要在
GetHandler
中迭代类型到处理程序的映射?您可以返回
bus.handlers[t]
,对于未定义的处理程序,这将返回
nil
。@mkb,因为我可能与