开发者

Casting back to more specialised interface

开发者 https://www.devze.com 2023-02-06 13:56 出处:网络
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

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 Phy开发者_StackOverflowsEntity 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?


Use a type assertion. For example,

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消