How do I initialize a composed struct in Go?

Viewed 11968

Let's say I have a struct with another struct embedded in it.

type Base struct {
    ID string
}

type Child struct {
    Base
    a int
    b int
}

When I go to initialize Child, I can't initialize the ID field directly.

// unknown field 'ID' in struct literal of type Child
child := Child{ ID: id, a: a, b: b }

I instead have to initialize the ID field separately.

child := Child{ a: 23, b: 42 }
child.ID = "foo"

This would seem to violate encapsulation. The user of Child has to know there's something different about the ID field. If I later moved a public field into an embedded struct, that might break initialization.

I could write a NewFoo() method for every struct and hope everyone uses that, but is there a way to use the struct literal safely with embedded structs that doesn't reveal some of the fields are embedded? Or am I applying the wrong pattern here?

1 Answers
Related