回答

收藏

转换回更专业的界面

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

我在写游戏。C   中,我将在  中储存所有物理类别BaseEntity 类数组。如果一个实体需要在世界上移动,它将从 中衍生出来BaseEntity 的 PhysEntity,但是添加了方法。我试图模仿这个:
1 b/ ^) m7 Z' N1 I[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。这种方法的合适替代品是什么?
, x6 v( r. r- x7 H& _                                                               
- T( I' r- O& D: U    解决方案:                                                                0 E0 ]/ h" o* g4 O2 u7 p
                                                                类型断言。
1 j) a9 n/ W, F2 D9 x* b: ^[code]original,ok := entity.(PhysEntity)if ok    println(original.b()code]
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则