0

#yyds干货盘点#【愚公系列】2022年08月 Go教学课程 030-结构体继承

 1 year ago
source link: https://blog.51cto.com/u_15437432/5634875
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、结构体继承

1.结构体继承的概念

继承是面向对象软件技术当中的一个概念,与多态、封装共为面向对象的三个基本特征。继承可以使得子类具有父类的属性和方法或者重新定义、追加属性和方法等。

但在go语言中并没继承的概念,只能通过组合来实现继承。组合就是通过对现有对象的拼装从而获得实现更为复杂的行为的方法。

  • 继承:一个struct嵌套了另外一个匿名的struct从而实现了继承。
  • 组合:一个struct嵌套了宁外一个struct的实例实现了组合。
type Animal  struct {

}

//继承
type Cat struct {
    //匿名
    *Animail
}

//组合
type Dog struct {
    animal Animal
}

2.结构体继承的案例

2.1 普通类型

package main

import "fmt"

type Student struct {
	Person // 匿名字段,只有类型,没有成员的名字
	score  float64
}
type Teacher struct {
	Person
	salary float64
}
type Person struct {
	id   int
	name string
	age  int
}

func main() {
	//var stu Student=Student{Person{100,"愚公",31},90}
	// 部分初始化
	// var stu Student=Student{score:100}
	var stu Student = Student{Person: Person{id: 100}}
	fmt.Println(stu)
	//fmt.Println(stu1)
}


#yyds干货盘点#【愚公系列】2022年08月 Go教学课程 030-结构体继承_字段

2.2 结构体继承指针类型

package main

import "fmt"

type Student struct {
	*Person // 匿名字段
	score   float64
}
type Person struct {
	id   int
	name string
	age  int
}

func main() {
	var stu Student = Student{&Person{101, "愚公", 18}, 90}
	fmt.Println(stu.name)
}

3.结构体继承成员值的修改

package main

import "fmt"

type Student struct {
	Person
	score float64
}
type Person struct {
	id   int
	name string
	age  int
}

func main() {

	var stu Student = Student{Person{101, "愚公1号", 18}, 90}
	var stu1 Student = Student{Person{102, "愚公2号", 18}, 80}
	stu.score = 100
	fmt.Println("愚公一号考试成绩:", stu.score)
	fmt.Println(stu1.score)
	fmt.Println(stu1.Person.id)
	fmt.Println(stu1.id)
}

#yyds干货盘点#【愚公系列】2022年08月 Go教学课程 030-结构体继承_面向对象_02

4.结构体的多重继承

package main

import "fmt"

type Student struct {
	Person
	score float64
}
type Person struct {
	Object
	name string
	age  int
}
type Object struct {
	id int
}

func main() {
	var stu Student
	stu.age = 18
	fmt.Println(stu.Person.age)
	stu.id = 101
	fmt.Println(stu.Person.Object.id)
}

#yyds干货盘点#【愚公系列】2022年08月 Go教学课程 030-结构体继承_面向对象_03

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK