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

时间:2015-11-25 04:50:30

标签: go encapsulation embedding

我有一个依赖于从另一个包导入的结构的项目,我将其称为TheirEntity

在下面的示例中,我(ahem)在TheirEntity中嵌入了MyEntity,这是TheirEntity的扩展,并增加了功能。

但是,我不想在TheirEntity结构中导出MyEntity,因为我宁愿消费者不直接访问TheirEntity

我知道Go嵌入与经典OOP中的继承不同,所以这可能不是正确的方法,但可以将嵌入式结构指定为" private",即使它们是导入的从另一个包?如何以更惯用的方式实现同​​样的目标?

// 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,
    }
}

1 个答案:

答案 0 :(得分:4)

  

[我]可以将嵌入式结构指定为“私有”,即使它们是从另一个包导入的吗?

没有

  

如何以更惯用的方式实现同​​样的目标?

通过非嵌入但将其作为未导出的命名字段。