小编典典

转换回更专业的界面

go

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

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())
}

这不会编译,因为它无法判断“实体”是一个 PhysEntity。这种方法的合适替代品是什么?


阅读 168

收藏
2021-12-23

共1个答案

小编典典

类型断言。例如,

original, ok := entity.(PhysEntity)
if ok {
    println(original.b())
}
2021-12-23