6.3 Composing Types by Struct Embedding
Consider the type ColoredPoint
:
import "image/color" type Point struct{ X, Y float64 } type ColoredPoint struct { Point Color color.RGBA }
We could have defined ColoredPoint
as a struct of three fields, but instead we
embedded a Point
to provide the X
and Y
fields. As we saw in
Section 4.4.3, embedding lets us take a syntactic shortcut to defining
a ColoredPoint
that contains all the fields of Point
, plus some
more. If we want, we can select the fields of ColoredPoint
that were
contributed by the embedded Point
without mentioning Point
:
var cp ColoredPoint cp.X = 1 fmt.Println(cp.Point.X) // "1" cp.Point.Y = 2 fmt.Println(cp.Y) // "2"
A similar ...
Get The Go Programming Language now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.