我有一个项目依赖于从另一个包导入的结构,我将称之为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 关注
- 135 浏览
添加回答
举报
0/150
提交
取消