投射回更专业的界面

发布于 2024-10-14 10:32:11 字数 760 浏览 3 评论 0原文

我正在用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

狂之美人 2024-10-21 10:32:11

使用类型断言。例如,

original, ok := entity.(PhysEntity)
if ok {
    println(original.b())
}

Use a type assertion. For example,

original, ok := entity.(PhysEntity)
if ok {
    println(original.b())
}
七度光 2024-10-21 10:32:11

具体来说,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文