0
点赞
收藏
分享

微信扫一扫

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

一、结构体继承

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)
}

在这里插入图片描述

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)
}

在这里插入图片描述

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)
}

在这里插入图片描述

举报

相关推荐

0 条评论