英文:
Casting back to more specialised interface
问题
我正在用Go语言编写一个游戏。在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)
// 在上面的一行出现错误:无法将physEnt(类型为PhysEntity)转换为Entity类型:
println(original.b())
}
这段代码无法编译,因为它无法确定'entity'是一个PhysEntity。有什么适合这种情况的替代方法吗?
英文:
I'm writing a game in go. In C++ I would store all my entity classes in an array of the BaseEntity class. If an entity needed to move about in the world it would be a PhysEntity which is derived from a BaseEntity, but with added methods. I tried to imitate this is 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())
}
This will not compile as it cant tell that 'entity' was a PhysEntity. What is a suitable alternative to this method?
答案1
得分: 125
使用type assertion。例如,
original, ok := entity.(PhysEntity)
if ok {
println(original.b())
}
英文:
Use a type assertion. For example,
original, ok := entity.(PhysEntity)
if ok {
println(original.b())
}
答案2
得分: 9
具体来说,Go语言的"interface"类型包含了传递给接口的对象的真实信息,因此将其转换为其他类型比C++的dynamic_cast或等效的Java的test-and-cast要便宜得多。
英文:
Specifically, the Go "interface" type has the information on what the object really was, that was passed by interface, so casting it is much cheaper than a C++ dynamic_cast or the equivalent java test-and-cast.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论