【问题标题】:Assign a variable to "label" type, or how to type cast between pointers将变量分配给“标签”类型,或如何在指针之间进行类型转换
【发布时间】:2019-02-28 04:43:03
【问题描述】:

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

type BaseType struct {
   id  uint64
   name string
}

type LabeledType1 BaseType
type LabeledType2 BaseType

整个链中有一个函数实际上并不关心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
}

现在当然不能编译:

cannot convert e (type *LabeledType1) to type BaseType

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

evt.(BaseType))

还有

BaseType(e)

我不能在BaseType 中使用bool

【问题讨论】:

  • 您似乎正试图将其用作多态性的一种形式,但事实并非如此。你实际上想要完成什么?在 Go 中可能有更好/更惯用的方式来完成它。

标签: go types interface casting


【解决方案1】:

使用(*BaseType)() type conversion*LabeledType1*LabeledType2 转换为*BaseType

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

Run it on the playground.

【讨论】:

  • 是的!!!就是这样,我尝试过BaseType(e),但这是指针和结构之间的不匹配,但不知道如何为指针实现它:) 谢谢!
  • 我已经编辑了问题标题,以便更清楚我实际要求的内容:)
猜你喜欢
  • 2012-04-24
  • 2020-07-30
  • 1970-01-01
  • 2019-06-16
  • 1970-01-01
  • 1970-01-01
  • 2010-09-30
  • 2019-12-09
  • 1970-01-01
相关资源
最近更新 更多