投射回更专业的界面
我正在用 Go 编写一个游戏。在 C++ 中,我将所有实体类存储在 BaseEntity 类的数组中。如果一个实体需要在世界上移动,那么它将是一个从 BaseEntity 派生的 PhysEntity,但添加了方法。我试图模仿这个 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())
}
这不会编译,因为它不能告诉“实体”是一个 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用类型断言。例如,
Use a type assertion. For example,
具体来说,Go“接口”类型具有有关对象实际是什么的信息,该对象是通过接口传递的,因此对其进行强制转换比 C++ 动态强制转换或等效的 java 测试和强制转换要便宜得多。
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.