Last Updated : 22 Jun, 2020
Output:
Universe is: MCU Universe is: DC
Let's first create the author
struct.
package main
import(
"fmt"
)
type author struct {
firstName string
lastName string
bio string
}
func(a author) fullName() string {
return fmt.Sprintf("%s %s", a.firstName, a.lastName)
}
The next step would be to create the blogPost
struct.
type blogPost struct {
title string
content string
author
}
func(b blogPost) details() {
fmt.Println("Title: ", b.title)
fmt.Println("Content: ", b.content)
fmt.Println("Author: ", b.author.fullName())
fmt.Println("Bio: ", b.author.bio)
}
Whenever one struct field is embedded in another, Go gives us the option to access the embedded fields as if they were part of the outer struct. This means that p.author.fullName()
in line no. 11 of the above code can be replaced with p.fullName()
. Hence the details()
method can be rewritten as below,
func(p blogPost) details() {
fmt.Println("Title: ", p.title)
fmt.Println("Content: ", p.content)
fmt.Println("Author: ", p.fullName())
fmt.Println("Bio: ", p.bio)
}
The main function of the program above creates a new author in line no. 31. A new post is created in line no. 36 by embedding author1
. This program prints,
Title: Inheritance in Go Content: Go supports composition instead of inheritance Author: Naveen Ramanathan Bio: Golang Enthusiast
Let's define the website
struct first. Please add the following code above the main function of the existing program and run it.
type website struct {
[] blogPost
}
func(w website) contents() {
fmt.Println("Contents of Website\n")
for _, v: = range w.blogPosts {
v.details()
fmt.Println()
}
}
Go doesn’t have inheritance – instead composition, embedding and interfaces support code reuse and polymorphism.,Further down the road your project might have grown to include more animals. At this point you can introduce polymorphism and dynamic dispatch using interfaces.,Object-oriented programming with inheritance,Inheritance in traditional object-oriented languages offers three features in one. When a Dog inherits from an Animal
If a Dog
needs some or all of the functionality of an Animal
,
simply use composition.
type Animal struct {
// …
}
type Dog struct {
beast Animal
// …
}
If the Dog
class inherits the exact behavior of an Animal
,
this approach can result in some tedious coding.
type Animal struct {
// …
}
func(a * Animal) Eat() {
…}
func(a * Animal) Sleep() {
…}
func(a * Animal) Breed() {
…}
type Dog struct {
beast Animal
// …
}
func(a * Dog) Eat() {
a.beast.Eat()
}
func(a * Dog) Sleep() {
a.beast.Sleep()
}
func(a * Dog) Breed() {
a.beast.Breed()
}
Go uses embedding for situations like this.
The declaration of the Dog
struct and it’s three methods can be reduced to:
type Dog struct {
Animal
// …
}