我有一个这样的结构,//// HandlerInfo is used by features in order to register a gateway handlertype 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,例如在我的内部StarboardReactionHandler或内部进行HandlerInfo?也许使用泛型或反射?我基本上只想尽量减少此处所需的语法/样板。
1 回答
慕婉清6462132
TA贡献1804条经验 获得超2个赞
你可以使用接口{}。(类型)
下面是一个例子:
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)
}
- 1 回答
- 0 关注
- 91 浏览
添加回答
举报
0/150
提交
取消