Be Careful with Go Struct Embedding

Go has a feature called struct embedding that allows you to compose types. It looks something like this: type Position struct { X int Y int } type Colour struct { R byte G byte B byte } type Rectangle struct { Position Colour Width int Height int } r := Rectangle{/* … */} // This works: fmt.Printf(“%d,%dn”, r.Position.X, r.Position.Y) // but so does this: fmt.Printf(“%d,%dn”, r.X, r.Y) But what do you think this code does? type FooService struct { URL string } type BarConnectionOptions struct { URL string } type BarService struct { BarConnectionOptions } type Options struct { FooService BarService } opts := Options{ FooService: FooService{URL: “abc.com”}, BarService: BarService{ BarConnectionOptions: BarConnectionOptions{ URL: “xyz.com”, }, }, } fmt.Println(opts.URL) I would expect…

Read more on Hacker News