Comprehending inheritance in Go

Go does not have inheritance. Composition is used in order to embed items (mostly structs) in one another. This is convenient when you have a baseline struct that is used for many different functions, with other structs that build on top of the initial struct.

We can describe some of the items in my kitchen to show how inheritance works.

We can initialize our program as shown in the following code block. In this block, we create two structs: 

Utensils: For the utensils I have in my drawers in my kitchen

Appliances: For the appliances I have in my kitchen

package main
import "fmt"

func main() {
type Utensils struct {
fork string
spoon string
knife string
}

type Appliances struct {
stove string
dishwasher string
oven string
}

I can next use Go's nested structuring to create a Kitchen struct that contains all of the utensils and appliances as follows:

    type Kitchen struct {
Utensils
Appliances
}

I can then fill my kitchen with the utensils and appliances that I have:

    bobKitchen := new(Kitchen)
bobKitchen.Utensils.fork = "3 prong"
bobKitchen.Utensils.knife = "dull"
bobKitchen.Utensils.spoon = "deep"
bobKitchen.Appliances.stove = "6 burner"
bobKitchen.Appliances.dishwasher = "3 rack"
bobKitchen.Appliances.oven = "self cleaning"
fmt.Printf("%+v ", bobKitchen)
}

Once all of these things are in, we can see the resulting output where my kitchen items (the Utensils and Appliances) are organized in my Kitchen struct. My Kitchen struct is then easily referenced later in other methods.

Having nested structs can be very practical for future extension. If I decided that I'd like to add other elements in my house to this structure, I could make a House struct and nest my Kitchen struct within the House struct. I could also compose structs for other rooms in my house and add them to the house struct as well. 

In the next section, we will explore reflection in Go.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.148.210