我正在写游戏。在C ++中,我将所有实体类存储在BaseEntity类的数组中。如果一个实体需要在世界中移动,那么它将是一个PhysEntity,它源自BaseEntity,但是添加了方法。我试图模仿这是:
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。什么是这种方法的合适替代方案?
答案 0 :(得分:96)
使用type assertion。例如,
original, ok := entity.(PhysEntity)
if ok {
println(original.b())
}
答案 1 :(得分:7)
具体来说,Go“interface”类型具有关于对象实际上是什么的信息,它是由接口传递的,因此转换它比C ++ dynamic_cast或等效的java test-and-cast便宜得多。