November 2017
Intermediate to advanced
670 pages
17h 35m
English
Software should be open for extension but closed for modification. Embedding fields in a struct allows us to extend one type with another. The object (CarWithSpare) that embedded the other (Car) has access to its fields and methods. The CarWithSpare object can call Car methods, but cannot modify the Car object's methods. Therefore, Go's types, while being open for extension, are closed for modification. Let's look at an example:
package carimport "fmt"type Car struct { Make string Model string}func (c Car) Tires() int { return 4 }func (c Car) PrintInfo() { fmt.Printf("%v has %d tires\n", c, c.Tires())}
We defined our Car type and two methods, Tires and PrintInfo. Next, we'll define our CarWithSpare type and embed the ...