Contents

Inheritance in GoLang

Contents

Inheritance is an important concept in OOP (Object-Oriented Programming). Since Golang does not support classes, there is no inheritance concept in GoLang. However, you can implement inheritance through struct embedding.

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main

import "fmt"

func main() {
	fmt.Println("Demo inheritance in GoLang!")
	customer := Customer{
		Person: Person{
			name: "John Doe",
			age:  30,
		},
		email:  "john@gmail.com",
		is_vip: true,
	}
	customer.Person.DisplayInfo()
	customer.DisplayInfo()
}

// region Person functions
type Person struct {
	name string
	age  int
}

func (u Person) DisplayInfo() {
	fmt.Printf("Name: %s, Age: %d\n", u.name, u.age)
}

// endregion User functions

// region Customer functions
type Customer struct {
	Person
	email  string
	is_vip bool
}

You can embed as many base structs as you want

Related Content