Casting back to more specialised interface

Go

Go Problem Overview


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?

Go Solutions


Solution 1 - Go

Use a type assertion. For example,

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

Solution 2 - Go

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser181351View Question on Stackoverflow
Solution 1 - GopeterSOView Answer on Stackoverflow
Solution 2 - GoweregamerView Answer on Stackoverflow