将任何接口作为参数时,简化 Go 中的转换

Simplify casting in Go when taking any interface as a parameter

我有一个这样的结构,

//
// HandlerInfo is used by features in order to register a gateway handler
type HandlerInfo struct {
    Fn     func(interface{})
    FnName string
    FnRm   func()
}

我想传递函数的地方:

func StarboardReactionHandler(e *gateway.MessageReactionAddEvent) {
 // foo
}

i := HandlerInfo{Fn: StarboardReactionHandler}

不幸的是,这会导致:

Cannot use 'StarboardReactionHandler' (type func(e *gateway.MessageReactionAddEvent)) as the type func(interface{})

我找到了这个解决方法:

func StarboardReactionHandler(e *gateway.MessageReactionAddEvent) {
 // foo
}

func handlerCast(e interface{}) {
    StarboardReactionHandler(e.(*gateway.MessageReactionAddEvent))
}

i := HandlerInfo{Fn: handlerCast}

有什么方法可以简化对 handlerCast 的需求,比如在我的 StarboardReactionHandlerHandlerInfo 中进行?也许使用泛型或反射?我基本上只想尽量减少此处所需的语法/样板文件。

你可以使用接口{}。(类型)

示例如下:

package main

import "fmt"

type HandlerInfo struct {
    Fn     func(interface{})
    FnName string
    FnRm   func()
}
type MessageReactionAddEvent = func(a, b int) int

func StarboardReactionHandler(e interface{}) {
    switch e.(type) {
    case MessageReactionAddEvent:
        fmt.Printf("%v\n", (e.(MessageReactionAddEvent))(1, 2))
    }

}
func add(a, b int) int {
    return a + b
}
func main() {
    i := HandlerInfo{Fn: StarboardReactionHandler}
    i.Fn(add)
}