In Go, embedding refers to the ability to embed one type into another, allowing us to achieve:
- Code reusability: Embedding is useful for sharing common behaviors between types without explicitly inheriting from a base class.
- Composition: It enables the composition of types, meaning that a type can include other types and, therefore, inherit their behaviors.
- Functionality extension: It is used to extend the functionality of an existing type by incorporating other types that provide additional features.
- Simplicity and clarity: It can simplify and make the design of types clearer by allowing a more modular and easy-to-understand structure.
If you are new to the world of Go, I recommend the following previous articles:
In this simple example, we have three structures:
- person: Common structure.
- student: Inherits from
person
and additionally adds the stringgrade
. - teacher: Inherits from
person
and additionally adds the intteaching_years
.
vi university.go
package main
import "fmt"
type person struct {
name string
age int
}
func (p person) introduction() {
fmt.Printf("Hello, I'm %s and I'm %d years old.\n", p.name, p.age)
}
type student struct {
person
grade string
}
func (s student) study() {
fmt.Printf("%s is studying in %s.\n", s.name, s.grade)
}
type teacher struct {
person
teaching_years int
}
func (t teacher) teaching() {
fmt.Printf("%s has been teaching %d years.\n", t.name, t.teaching_years)
}
func main() {
student := student{
person: person{
name: "Ana",
age: 20,
},
grade: "engineering",
}
teacher := teacher{
person: person{
name: "Joe",
age: 30,
},
teaching_years: 10,
}
student.introduction()
student.study()
fmt.Println("-----")
teacher.introduction()
teacher.teaching()
}
Let’s execute the code:
go run university.go
We can see how each object shares the fields defined in the person
structure (name/age) and also has their respective specific additional fields (grade/teaching_years), besides person
, student
and teacher
structures have a common function introduction
and one own function study
and teaching respectively
due to the
Go methods
:
Hello, I'm Ana and I'm 20 years old.
Ana is studying in engineering.
-----
Hello, I'm Joe and I'm 30 years old.
Joe has been teaching 10 years.