回归到更专业化的界面 [英] Casting back to more specialised interface

查看:75
本文介绍了回归到更专业化的界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个游戏。在C ++中,我会将所有实体类存储在BaseEntity类的数组中。如果一个实体需要在世界中移动,它将是一个从BaseEntity派生的PhysEntity,但是增加了方法。我试图模仿这是去:

 包主

实体接口{
a ()字符串
}

类型PhysEntity接口{
实体
b()字符串
}

类型BaseEntity struct {}
func(e * BaseEntity)a()string {returnHello}

BasePhysEntity struct {BaseEntity}
func(e * BasePhysEntity)b()string {return 世界! }

func main(){
physEnt:= PhysEntity(new(BasePhysEntity))
entity:= Entity(physEnt)
print(entity.a() )
original:= PhysEntity(entity)
//上面的错误:无法将physEnt(类型PhysEntity)转换为类型实体:
println(original.b())
}

这不会编译,因为它不能说'实体'是PhysEntity。什么是这种方法的一个合适的替代方案?

使用键入断言。例如,

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


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?

解决方案

Use a type assertion. For example,

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

这篇关于回归到更专业化的界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆