dtg
dtg

Reputation: 1853

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.

In the example below, I (ahem) embed TheirEntity in MyEntity, which is an extension of TheirEntity, with added functionality.

However, I don't want to export TheirEntity in the MyEntity structure, as I would rather the consumer not access TheirEntity directly.

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

Upvotes: 9

Views: 3944

Answers (3)

jub0bs
jub0bs

Reputation: 66244

Since the question was asked, Go 1.9 saw the addition of type aliases to the language. Through an unconventional use of type aliases, you can actually have your cake and eat it too!

First, declare an unexported alias for the third-party type you wish to embed in your struct:

type theirEntity = TheirEntity

Then, simply embed that alias instead of the original type:

type MyEntity struct {
    *theirEntity
    color string
}

(Playground)

Upvotes: 20

Greg Dennis
Greg Dennis

Reputation: 85

Like this:

type MyEntity struct {
    *privateTheirEntity
}

type privateTheirEntity struct {
    *TheirEntity
}

Upvotes: 6

Volker
Volker

Reputation: 42413

[I]s it possible to specify embedded structs as "private", even if they are imported from another package?

No.

How might one achieve the same thing in a more idiomatic fashion?

By not-embedding but making it a unexported named field.

Upvotes: 2

Related Questions