나는 게임을 쓰고있다. C++에서는 모든 엔티티 클래스를 BaseEntity 클래스의 배열에 저장합니다. 엔티티가 세계에서 움직일 필요가 있다면 BaseEntity에서 파생 된 PhysEntity가 될 것이지만 메소드가 추가됩니다. 이 '실체'는 PhysEntity라고 말할 기운으로이 컴파일되지 않습니다더 특수화 된 인터페이스로 캐스팅하기
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())
}
:이 모방하려고하는 것은 이동합니다. 이 방법에 대한 적절한 대안은 무엇입니까?
타입 어설 션이 비싸다는 것을 알고 있습니까? BaseEntity에 변수가있는 유형을 추적하는 것이 나에게 가치가 있습니까? –
유형 어설 션은 저렴합니다. – rog
내가 이것을 시도 할 때, "type assertion"이 "interface"에 유효하기 때문에 잘못된 유형의 선언 (non-interface type .. .. 왼쪽에) " – Zac