给定以下类型:
type Event interface{}
type ActionResultEvent struct {
Result string
}
type ActionSuccessEvent ActionResultEvent
type ActionFailureEvent ActionResultEvent
type eventHandleFunc func(e Event)
eventHandleFunc
我的目标是为具体类型ActionSuccessEvent
以及ActionFailureEvent
更抽象的类型提供事件处理程序(类型) ActionResultEvent
。后者我想同时用于ActionSuccessEvent
s 和ActionFailureEvent
s。
现在我的想法是将Event
接口类型转换为我想要处理的结构,这对于具体类型非常有效。
// Working perfectly fine
func(e Event) {
event := e.(ActionFailureEvent)
fmt.Println(event.Result)
} (ActionFailureEvent{ Result: "failure" })
func(e Event) {
event := e.(ActionSuccessEvent)
fmt.Println(event.Result)
} (ActionSuccessEvent{ Result: "success" })
现在接受ActionResultEvent
s 的处理程序呢?我最喜欢的应该是这样的:
func(e Event) {
event := e.(ActionResultEvent)
fmt.Println(event.Result)
} (ActionSuccessEvent{ Result: "success" })
这显然像e
type一样恐慌ActionSuccessEvent
。
然后我们当然可以转换为初始类型并返回中间类型:
// Works but would that would need to change whenever new types "extending"
// ActionResultEvent are added
func(e Event) {
var resultEvent ActionResultEvent
switch e.(type) {
case ActionSuccessEvent:
resultEvent = ActionResultEvent(e.(ActionSuccessEvent))
case ActionFailureEvent:
resultEvent = ActionResultEvent(e.(ActionFailureEvent))
}
fmt.Println(resultEvent.Result)
} (ActionSuccessEvent{ Result: "success" })
从我的角度来看,另一个非常好的方法是:
// Error: use of e.(type) outside type switch
func(e Event) {
resultEvent := ActionResultEvent(e.(type))
} (ActionSuccessEvent{ Result: "success" })
有人能想到一个顺利的解决方案吗?附带说明:如果处理程序在运行时在类型转换失败时发生恐慌,我很高兴,因为包装器将从中恢复。
这是上面操场上的示例代码。谢谢!