给定以下类型:
type Event interface{}
type ActionResultEvent struct {
Result string
}
type ActionSuccessEvent ActionResultEvent
type ActionFailureEvent ActionResultEvent
type eventHandleFunc func(e Event)
我的目标是为具体类型 ActionSuccessEvent
、ActionFailureEvent
以及更多抽象 ActionResultEvent
。我想将后者用于 ActionSuccessEvent
和 ActionFailureEvent
。
现在我的想法是将 Event
接口(interface)类型转换为我想要处理的结构,这非常适合具体类型。
// 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
怎么样?我最喜欢的是这个:
func(e Event) {
event := e.(ActionResultEvent)
fmt.Println(event.Result)
} (ActionSuccessEvent{ Result: "success" })
这显然是 panic ,因为 e
是 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" })
有人能想出一个顺利的解决方案吗?一方面说明:如果处理程序在运行时每当类型转换失败时出现 panic ,我会很高兴,因为包装器将从中恢复。
这是上面关于 playground 的示例代码.谢谢!
最佳答案
虽然我在这里得到了反对票,但我相信这可能会引起其他人的兴趣。所以我决定将解决方案发布到我认为有效的地方:参见 playground
如果这是不好的做法或者不是做事的“可行方式”,我真的很乐意得到一些反馈。谢谢!
关于Golang 类型断言/转换为中间结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49483263/