回答

收藏

转换回更专业的界面

技术问答 技术问答 367 人阅读 | 0 人回复 | 2023-09-12

我在写游戏。C   中,我将在  中储存所有物理类别BaseEntity 类数组。如果一个实体需要在世界上移动,它将从 中衍生出来BaseEntity 的 PhysEntity,但是添加了方法。我试图模仿这个:
$ n9 \( H  c; W; g, b+ H/ U/ z[code]package maintype 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()code]因为不能判断实体是 PhysEntity。这种方法的合适替代品是什么?6 K0 \% p% P' f
                                                               
6 }: v/ q: H: D0 h- i6 Z0 F    解决方案:                                                               
% e# J8 Y5 y* d                                                                类型断言。
) _7 a6 I7 @3 N. f3 B1 G[code]original,ok := entity.(PhysEntity)if ok    println(original.b()code]
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则