我正在写游戏。在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。什么是该方法的合适替代方法?
使用类型断言。例如,
original, ok := entity.(PhysEntity) if ok { println(original.b()) }