【问题标题】:Casting back to more specialised interface回溯到更专业的界面
【发布时间】:2023-04-09 22:18:01
【问题描述】:

我正在编写一个围棋游戏。在 C++ 中,我会将所有实体类存储在 BaseEntity 类的数组中。如果一个实体需要在世界上移动,它会是一个从 BaseEntity 派生的 PhysEntity,但具有附加的方法。我试图模仿这是go:

package main

type Entity interface {
    a() string
}

type PhysEntity interface {
    Entity
    b() string
}

type BaseEntity struct { }
func (e *BaseEntity) a() string { return "Hello " }

type BasePhysEntity struct { BaseEntity }
func (e *BasePhysEntity) b() string { return " World!" }

func main() {
    physEnt := PhysEntity(new(BasePhysEntity))
    entity := Entity(physEnt)
    print(entity.a())
    original := PhysEntity(entity)
// ERROR on line above: cannot convert physEnt (type PhysEntity) to type Entity:
    println(original.b())
}

这将无法编译,因为它无法判断 'entity' 是一个 PhysEntity。这种方法有什么合适的替代方法?

【问题讨论】:

    标签: go


    【解决方案1】:

    使用type assertion。例如,

    original, ok := entity.(PhysEntity)
    if ok {
        println(original.b())
    }
    

    【讨论】:

    • 你知道类型断言的使用成本高吗?是否值得我使用 BaseEntity 中的变量来跟踪类型?
    • 类型断言很便宜。
    • 当我尝试这个时,我得到一个错误:invalid type assertion .. (non-interface type .. on left)
    • @Zac 因为“类型断言”在“接口”上有效,您的值不是“接口”。
    【解决方案2】:

    具体来说,Go 的“接口”类型包含对象的真实信息,由接口传递,因此转换它比 C++ dynamic_cast 或等效的 java test-and-cast 便宜得多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-15
      相关资源
      最近更新 更多