簡體   English   中英

從另一個包導入結構時的私有嵌入結構

[英]Private embedded struct when importing a struct from another package

我有一個項目依賴於從另一個包導入的結構,我將其命名為TheirEntity

在下面的例子中,I(啊哈)嵌入TheirEntityMyEntity ,這是一個擴展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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM