我有一個項目依賴于從另一個包導入的結構,我將稱之為TheirEntity.在下面的示例中,我(咳咳)嵌入TheirEntity了MyEntity,它是 的擴展TheirEntity,具有附加功能。但是,我不想TheirEntity在MyEntity結構中導出,因為我寧愿消費者不TheirEntity直接訪問。我知道 Go 嵌入與經典 OOP 中的繼承不同,所以這可能不是正確的方法,但是是否可以將嵌入的結構指定為“私有”,即使它們是從另一個包導入的?如何以更慣用的方式實現同樣的事情?// TheirEntity contains functionality I would like to use...type TheirEntity struct { name string}func (t TheirEntity) PrintName() { fmt.Println(t.name)}func NewTheirEntity(name string) *TheirEntity { return &TheirEntity{name: name}}// ... by embedding in MyEntitytype MyEntity struct { *TheirEntity // However, I don't want to expose // TheirEntity directly. How to embed this // without exporting and not changing this // to a named field? color string}func (m MyEntity) PrintFavoriteColor() { fmt.Println(m.color)}func NewMyEntity(name string, color string) *MyEntity { return &MyEntity{ TheirEntity: NewTheirEntity(name), color: color, }}
- 2 回答
- 0 關注
- 161 瀏覽
添加回答
舉報
0/150
提交
取消