-1

给定以下类型:

type Event interface{}

type ActionResultEvent struct {
    Result string
}

type ActionSuccessEvent ActionResultEvent
type ActionFailureEvent ActionResultEvent

type eventHandleFunc func(e Event)

eventHandleFunc我的目标是为具体类型ActionSuccessEvent以及ActionFailureEvent更抽象的类型提供事件处理程序(类型) ActionResultEvent。后者我想同时用于ActionSuccessEvents 和ActionFailureEvents。

现在我的想法是将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" }) 

现在接受ActionResultEvents 的处理程序呢?我最喜欢的应该是这样的:

func(e Event) {
  event := e.(ActionResultEvent)
  fmt.Println(event.Result)
} (ActionSuccessEvent{ Result: "success" })    

这显然像etype一样恐慌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" })

有人能想到一个顺利的解决方案吗?附带说明:如果处理程序在运行时在类型转换失败时发生恐慌,我很高兴,因为包装器将从中恢复。

这是上面操场上的示例代码。谢谢!

4

1 回答 1

0

尽管我在这里投了反对票,但我相信其他人可能会对此感兴趣。所以我决定将解决方案发布到我想出的工作:看操场

如果这是不好的做法,或者不是做事的“好方法”,我会很高兴得到一些反馈。谢谢!

于 2018-03-26T06:04:06.370 回答