官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 肥西县| 蒲江县| 安义县| 萍乡市| 兴宁市| 澄城县| 诸城市| 绍兴市| 汕头市| 洛南县| 阳曲县| 陵川县| 玉龙| 环江| 卢龙县| 承德县| 二连浩特市| 红原县| 九寨沟县| 临颍县| 南靖县| 辛集市| 阜宁县| 台东市| 筠连县| 望江县| 历史| 虞城县| 日土县| 深圳市| 巴马| 杭州市| 沙坪坝区| 高邮市| 西林县| 黎城县| 中山市| 醴陵市| 格尔木市| 铜陵市| 郎溪县|