Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,
    }
}
like image 303
dtg Avatar asked Apr 15 '26 10:04

dtg


2 Answers

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)

like image 117
jub0bs Avatar answered Apr 16 '26 23:04

jub0bs


Like this:

type MyEntity struct {
    *privateTheirEntity
}

type privateTheirEntity struct {
    *TheirEntity
}
like image 45
Greg Dennis Avatar answered Apr 16 '26 23:04

Greg Dennis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!