简体   繁体   English

从另一个包导入结构时的私有嵌入结构

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

I have a project which relies on a struct imported from another package, which I will call TheirEntity .我有一个项目依赖于从另一个包导入的结构,我将其命名为TheirEntity

In the example below, I (ahem) embed TheirEntity in MyEntity , which is an extension of TheirEntity , with added functionality.在下面的例子中,I(啊哈)嵌入TheirEntityMyEntity ,这是一个扩展TheirEntity ,具有附加功能。

However, I don't want to export TheirEntity in the MyEntity structure, as I would rather the consumer not access TheirEntity directly.但是,我不想在MyEntity结构中导出TheirEntity体,因为我宁愿消费者不直接访问TheirEntity

I know that Go embedding is not the same as inheritance in classical OOP, so maybe this is not the correct approach, but is it possible to specify embedded structs as "private", even if they are imported from another package?我知道 Go 嵌入与经典 OOP 中的继承不同,所以这可能不是正确的方法,但是是否可以将嵌入的结构指定为“私有”,即使它们是从另一个包导入的? How might one achieve the same thing in a more idiomatic fashion?如何以更惯用的方式实现同​​样的事情?

// 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]s it possible to specify embedded structs as "private", even if they are imported from another package? [I]是否可以将嵌入式结构指定为“私有”,即使它们是从另一个包中导入的呢?

No. 没有。

How might one achieve the same thing in a more idiomatic fashion? 如何以一种惯用的方式实现同​​一件事?

By not-embedding but making it a unexported named field. 通过不嵌入,但使其成为未导出的命名字段。

Like this:像这样:

type MyEntity struct {
    *privateTheirEntity
}

type privateTheirEntity struct {
    *TheirEntity
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM