Inheritance means inheriting the properties of the superclass into the base class and is one of the most important concepts in Object-Oriented Programming. Since Golang does not support classes, so inheritance takes place through struct embedding. We cannot directly extend structs but rather use a concept called composition where the struct is used to form other objects. So, you can say there is No Inheritance Concept in Golang.
In composition, base structs can be embedded into a child struct and the methods of the base struct can be directly called on the child struct as shown in the following example.
Example 1:
package main
import (
"fmt"
)
type Comic struct {
Universe string
}
func (comic Comic) ComicUniverse() string {
return comic.Universe
}
type Marvel struct {
Comic
}
type DC struct {
Comic
}
func main() {
c1 := Marvel{
Comic{
Universe: "MCU" ,
},
}
fmt.Println( "Universe is:" , c1.ComicUniverse())
c2 := DC{
Comic{
Universe : "DC" ,
},
}
fmt.Println( "Universe is:" , c2.ComicUniverse())
}
|
Output:
Universe is: MCU
Universe is: DC
Multiple inheritances take place when the child struct is able to access multiple properties, fields, and methods of more than one base struct. Here the child struct embeds all the base structs as shown through the following code:
Example 2:
package main
import (
"fmt"
)
type first struct {
base_one string
}
type second struct {
base_two string
}
func (f first) printBase1() string{
return f.base_one
}
func (s second) printBase2() string{
return s.base_two
}
type child struct {
first
second
}
func main() {
c1 := child{
first{
base_one: "In base struct 1." ,
},
second{
base_two: "\nIn base struct 2.\n" ,
},
}
fmt.Println(c1.printBase1())
fmt.Println(c1.printBase2())
}
|
Output:
In base struct 1.
In base struct 2.