Inheritance in Go

  1. Implied inheritance using interfaces with Polymorphism
  2. Inheritance Embedding

Implied inheritance using interfaces with Polymorphism

package mainimport "fmt"type sleeper interface {
Sleep()
}
type Cat struct{}func (c *Cat) Sleep() {
fmt.Println("purrrrrr")
}
type Dog struct{}func (d *Dog) Sleep() {
fmt.Println("brrrrr")
}
func main() {
pets := []sleeper{new(Cat), new(Dog)}
for _, x := range pets {
x.Sleep()
}
var pussyCat1 sleeper
pussyCat1 = new(Cat)
pussyCat1.Sleep()
var tiger sleeper
tiger = &Dog{}
tiger.Sleep()
// This will not work
// var doggy sleeper
// doggy = Dog{}
// doggy.Sleep()
}

Inheritance by Embedding

package mainimport "fmt"type livingBeings interface {
GetLivingBeing() string
}
type species interface {
livingBeings
GetSpecies() string
}
type human struct {
species
Name string
}
type person struct {
human
age int
}
func (p *person) GetSpecies() string {
return "human"
}
func (h *human) GetLivingBeing() string {
return "human being"
}
func main() {
alen := person{
human: human{
Name: "Alen",
},
age: 10,
}
fmt.Println(alen.Name)
fmt.Println(alen.age)
fmt.Println(alen.GetSpecies())
fmt.Println(alen.GetLivingBeing())
}

References

Foot note

Buy Me A Coffee

--

--

--

Software Engineer @ Google

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Our Dev Shop tries MobiScroll

You Can’t Trick The Hackerman.

Understanding the Three Main Concepts Enabling a Data Center or IT Setup

Creating blog with Orchid (Part 4) — managing pages

Timing Freed from Processing Speed

MOCK API’s

Writing Better API Documentation

CAST AI vs. Cloudability for Cloud Cost Optimization

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alen Alex

Alen Alex

Software Engineer @ Google

More from Medium

Watch Out for These Tricky Things in Go

Apply Dependency Injection with Uber/Fx Golang

When and Where to Use Pointers in Go

An OpenMP-inspired approach to parallelizing loops in Go