0

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

 1 year ago
source link: https://blog.51cto.com/u_15437432/5638870
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.

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

精选 原创

愚公搬代码 2022-08-31 21:15:06 博主文章分类:愚公系列-Go教学课程 ©著作权

文章标签 子类 父类 f5 文章分类 Go语言 编程语言 yyds干货盘点 阅读数195

一、结构体方法继承

1.继承的概念

继承是指一个子类(或称为派生类)继承父类(或称为基类)的特征(属性和操作)。继承是面向对象程序设计时实现代码复用的重要手段,它允许在原有的类的基础上进行扩展,增加功能,这样新产生的类称为子类。

2.go中的继承

但在Go 语言本身并不支持继承。但可以使用组合的方法,实现类似继承的效果。Go 语言中,把一个结构体嵌入到另一个结构体的方法,称之为组合。

3.方法继承

package main

import "fmt"

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

func (p *Person) PrintInfo() {
	fmt.Println(*p)
}

func main() {
	stu := Student{Person{101, "张三", 18}, 90}
	stu.PrintInfo()
}

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

4.方法继承案例

package main

import "fmt"

//记者:我叫张三 ,我的爱好是偷拍,我的年龄是34,我是一个男狗仔。
//程序员:我叫孙全,我的年龄是23,我是男生,我的工作年限是 3年。
// 1: 定义父类

type Person struct {
	name string
	age  int
	sex  string
}

// 2: 给父类添加方法。
func (p *Person) SetValue(userName string, userAge int, userSex string) {
	p.sex = userSex
	p.age = userAge
	p.name = userName
}

// 3: 定义相应的子类。
// 记者类
type Rep struct {
	Person
	Hobby string // 爱好
}

func (r *Rep) RepSayHello(h string) {
	r.Hobby = h
	fmt.Printf("我叫%s ,我的爱好是%s,我的年龄是%d,我是一个%s记者\n", r.name, r.Hobby, r.age, r.sex)
}

// 程序员类
type Pro struct {
	Person
	WorkYear int
}

func (p *Pro) ProSayHello(workYear int) {
	p.WorkYear = workYear
	fmt.Printf("我叫%s,我的年龄是%d,我是%s,我的工作年限是 %d年\n", p.name, p.age, p.sex, p.WorkYear)
}

// 4: 给子类添加相应的方法
// 5: 展示效果

func main() {
	var rep Rep
	rep.SetValue("小黄", 35, "男")
	rep.RepSayHello("跟拍")

	var pro Pro
	pro.SetValue("小菊", 28, "男")
	pro.ProSayHello(3)
}
#yyds干货盘点#【愚公系列】2022年08月 Go教学课程 032-结构体方法继承_f5_02
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK