[英]Private embedded struct when importing a struct from another package
我有一個項目依賴於從另一個包導入的結構,我將其命名為TheirEntity
。
在下面的例子中,I(啊哈)嵌入TheirEntity
在MyEntity
,這是一個擴展TheirEntity
,具有附加功能。
但是,我不想在MyEntity
結構中導出TheirEntity
體,因為我寧願消費者不直接訪問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 MyEntity
type 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,
}
}
[I]是否可以將嵌入式結構指定為“私有”,即使它們是從另一個包中導入的呢?
沒有。
如何以一種慣用的方式實現同一件事?
通過不嵌入,但使其成為未導出的命名字段。
像這樣:
type MyEntity struct {
*privateTheirEntity
}
type privateTheirEntity struct {
*TheirEntity
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.