将变量分配给"label"类型,或者如何在指针之间键入cast

fab*_*ous 1 types casting interface go

我有两个相同的结构,为消除歧义的目的有不同的类型:

type BaseType struct {
   id  uint64
   name string
}

type LabeledType1 BaseType
type LabeledType2 BaseType
Run Code Online (Sandbox Code Playgroud)

整个链中有一个功能实际上并不关心LabeledType它,它只适用于BaseType(因为它与两者完全相同).事件的发送者必须发送标记类型,而不是基类型,因为实际类型定义了一些后行为.

func handle(evt interface{}) error {
  switch e := evt.(type) {
  case *LabeledType1: 
    return handleBaseEvent(e)
  case *LabeledType2:
    return handleBaseEvent(e)
  //there are other types
  case *OtherType:
      return handleOtherType(e)
  } 
}

func handleBaseEvent(evt *BaseType) {
   //do stuff
}
Run Code Online (Sandbox Code Playgroud)

现在当然这不编译:

cannot convert e (type *LabeledType1) to type BaseType
Run Code Online (Sandbox Code Playgroud)

但我想知道,就我理解这个概念而言,这两种类型都是可分配的,所以应该有一些简单的转换?我尝试过类型转换:

evt.(BaseType))

并且

BaseType(e)

我不能用bool里面的东西BaseType.

Cer*_*món 5

使用(*BaseType)() 类型转换来转换*LabeledType1,并*LabeledType2*BaseType:

func handle(evt interface{}) error {
    switch e := evt.(type) {
    case *LabeledType1:
        return handleBaseEvent((*BaseType)(e))
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

在操场上跑吧.