- Hands-On Full Stack Development with Go
- Mina Andrawos
- 236字
- 2021-07-02 12:33:32
Type embedding
But what if you would like a struct to inherit the methods of another struct? The closest feature that the Go language offers to the concept of inheritance is known as type embedding. This feature is best explained through an example. Let's go back to the Person struct type:
type Person struct{
name string
age int
}
func (p Person) GetName()string{
return p.name
}
func (p Person) GetAge()int{
return p.age
}
Now, let's say that we would like to create a new struct type called Student, which has all the properties and methods of Person, plus some more:
type Student struct{
Person
studentId int
}
func (s Student) GetStudentID()int{
return s.studentId
}
Notice that in the preceding code, we included the type Person inside the struct definition of type Student, without specifying a field name. This will effectively make the Student type inherit all the exported methods and fields of the Person struct type. In other words, we can access the methods and fields of Person directly from an object of type Student:
s := Student{}
//This code is valid, because the method GetAge() belongs to the embedded type 'Person':
s.GetAge()
s.GetName()
In Go, when a type gets embedded inside another type, the exported methods and fields of the embedded type are said to be promoted to the parent or embedding type.
Let's explore how to build interfaces in Go in the next section.
- PostgreSQL for Data Architects
- Apache Spark 2.x Machine Learning Cookbook
- QTP自動化測試進階
- 基于Swift語言的iOS App 商業(yè)實戰(zhàn)教程
- Building Minecraft Server Modifications
- Python Data Structures and Algorithms
- NGINX Cookbook
- Mastering Xamarin.Forms(Second Edition)
- PHP 7從零基礎到項目實戰(zhàn)
- Python從入門到精通(第3版)
- Hadoop大數(shù)據(jù)分析技術
- HTML+CSS+JavaScript網(wǎng)頁制作:從入門到精通(第4版)
- Practical Predictive Analytics
- Python Web自動化測試設計與實現(xiàn)
- Software-Defined Networking with OpenFlow(Second Edition)