Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 回归到更专业的界面_Go - Fatal编程技术网

Go 回归到更专业的界面

Go 回归到更专业的界面,go,Go,我正在用围棋写一个游戏。在C++中,我将把所有的实体类存储在一个基本实体类的数组中。如果一个实体需要在世界上四处移动,它将是一个从基本实体派生的物理实体,但带有附加的方法。我试着模仿这句话: package main type Entity interface { a() string } type PhysEntity interface { Entity b() string } type BaseEntity struct { } func (e *BaseE

我正在用围棋写一个游戏。在C++中,我将把所有的实体类存储在一个基本实体类的数组中。如果一个实体需要在世界上四处移动,它将是一个从基本实体派生的物理实体,但带有附加的方法。我试着模仿这句话:

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())
}
这将不会编译,因为它不能告诉“实体”是一个实体。此方法的合适替代方法是什么?

使用。比如说,

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

具体来说,GO“接口”类型有关于对象真正是什么的信息,它被接口传递,因此它比C++动态压缩或等价java测试和CAST要便宜得多。是否值得我使用BaseEntity中的变量跟踪类型?类型断言很便宜。当我尝试此操作时,我得到一个错误:

无效的类型断言。。(非接口类型..左侧)
@Zac因为“类型断言”在“接口”上有效,所以您的值不是“接口”。