71 go
我正在写一个游戏.在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())
}
Run Code Online (Sandbox Code Playgroud)
这不会编译,因为它不能告诉'实体'是一个PhysEntity.什么是这种方法的合适替代品?
pet*_*rSO 107
使用类型断言.例如,
original, ok := entity.(PhysEntity)
if ok {
println(original.b())
}
Run Code Online (Sandbox Code Playgroud)