Embedding Structs in Go

Pavel Belokon - Sep 5 - - Dev Community

Since Go lacks traditional inheritance and objects, it still adheres closely to object-oriented principles. Instead of using objects, we use structs, and instead of inheritance, we use embedding.

Example:

type Milk struct {
    MilkType  // Type of milk
}

type Cheese struct {
    Milk
    Time time.Time
}

cheese := Cheese{Time: "10 years"}
cheese.MilkType // Accesses the type of milk
Enter fullscreen mode Exit fullscreen mode

In this example, you can see how we can access the Milk struct from Cheese. This approach is simple to write and easy to understand.

So far I really enjoy Go 😀

. . .
Terabox Video Player