savo.la

2019-11-23

Go trick: obscure embedded field

type P struct {
    X int
    Y int
}

type C struct {
    P
    Z int
}

func main() {
    var c C

    _ = c.Z
    _ = c.Y
    _ = c.X
}

Because P is embedded into C anonymously, its fields are directly accessible. If access to an inherited field should be discouraged, direct access to it can be prevented like this:

type blocker struct {
    X struct{}
}

type P struct {
    X int
    Y int
}

type C struct {
    P
    Z int
    blocker
}

func main() {
    var c C

    _ = c.Z
    _ = c.Y
    _ = c.X   // Error: ambiguous selector.
    _ = c.P.X // Still works.
}

Unfortunately, the size of C is increased, even if the embedded struct is empty.

Timo Savola