Unlike C++ and JAVA, the Go language has inheritance keywords. Go does not directly support inheritance, but we can use structure nesting to simulate inheritance, that is, indirectly support inheritance .
The role of inheritance:
- Avoid duplication of code;
- Extend the functionality of the class.
The meaning of inheritance:
- Subclasses can have their own attributes and methods, or they can override existing methods of the class;
- The subclass can directly access all the properties and methods of the class.
Ways to implement inheritance
- The form of using anonymous fields is to simulate the inheritance relationship. When simulating the aggregation relationship, a structure with a name must be used as the field;
- The fields that belong to the anonymous structure in the structure are called promoted fields, because they can be accessed as if they belong to a structure with anonymous structure fields;
- In other words, the fields in the class are promoted fields.
Take the structure Student inheriting Person as an example, the code is as follows:
//myStruct.go
package main
import (
"fmt"
)
type Person struct {
Name string
Age int
Sex string
}
type Student struct {
Person //采用匿名字段,模拟继承关系
SchoolName string
}
func main() {
//fmt.Println("Hello World!")
//1、初始化Person
p1 := Person{"Steven", 35, "男"}
fmt.Println(p1)
fmt.Printf("p1: %T, %+v\n", p1, p1)
fmt.Println("--------------------")
//2、初始化Student
//写法1:
s1 := Student{p1, "武汉大学"}
fmt.Println(s1)
fmt.Printf("s1: %T, %+v\n", s1, s1)
fmt.Println("--------------------")
//写法2:
s2 := Student{Person{"Josh", 30, "男"}, "华中科技大学"}
fmt.Println(s2)
fmt.Printf("s2:%T, %+v\n", s2, s2)
fmt.Println("--------------------")
//写法3:
s3 := Student{Person: Person{
Name: "Penn",
Age: 19,
Sex: "男",
},
SchoolName: "武汉理工大学",
}
fmt.Println(s3)
fmt.Printf("s3: %T, %+v\n", s3, s3)
fmt.Println("-------------------")
//写法4:
s4 := Student{}
s4.Name = "Daniel"
s4.Sex = "男"
s4.Age = 12
s4.SchoolName = "剑桥大学"
fmt.Println(s4)
fmt.Printf("s4: %T, %+v\n", s4, s4)
fmt.Println("-------------------")
}
The effect is as follows: