2

#yyds干货盘点#【愚公系列】2022年09月 Go教学课程 033-结构体方法重写、方法值、方法...

 2 years ago
source link: https://blog.51cto.com/u_15437432/5656692
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.
neoserver,ios ssh client

#yyds干货盘点#【愚公系列】2022年09月 Go教学课程 033-结构体方法重写、方法值、方法表达式

精选 原创

愚公搬代码 2022-09-06 23:58:34 博主文章分类:愚公系列-Go教学课程 ©著作权

文章标签 子类 方法重写 方法名 文章分类 Go语言 编程语言 yyds干货盘点 阅读数219

一、结构体方法重写和方法值

1.方法重写

方法重写又称方法覆盖。方法重写概念方法的重写是指两个方法的返回值、方法名、参数的类型和个数相同(子类重写父类的方法)。方法的重写,不能发生在同类中,只能发生在子类中。若子类中的方法与父类中的某一方法具有相同的方法名、返回类型和参数表,则新方法将覆盖原有的方法。

package main

import "fmt"

type Person struct {
	name string
	age  int
}

func (p *Person) PrintInfo() {
	fmt.Println("这是父类中的方法")
}

type Student struct {
	Person
	score float64
}

func (p *Student) PrintInfo() {
	fmt.Println("这是子类中的方法")
}

func main() {
	var stu Student
	stu.PrintInfo() // 如果父类中的方法名称与子类中的方法名称一致,那么通过子类的对象调用的是子类中的方法。方法重写
	stu.Person.PrintInfo()
}
#yyds干货盘点#【愚公系列】2022年09月 Go教学课程 033-结构体方法重写、方法值、方法表达式_子类

2.方法值和方法表达式

  • 方法值:相当于方法指针
  • 方法表达式:显示的传参(这里没有继承概念)

方法值和方法表达式,也就是“方法对象赋值给变量”
两种使用方式:

  • 1)隐式调用, struct实例获取方法对象---->方法值
  • 2)显示调用, struct类型获取方法对象, 须要传递struct实例对象作为参数。---->方法表达式
package main

import "fmt"

type Person struct {
	name string
	age  int
}

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

func main() {
	per := Person{"愚公", 18}
	per.PrintInfo()

	//方法值。
	//f := per.PrintInfo
	//fmt.Printf("%T",f)
	//f()
	//方法表达式
	f := (*Person).PrintInfo
	f(&per)

}

#yyds干货盘点#【愚公系列】2022年09月 Go教学课程 033-结构体方法重写、方法值、方法表达式_子类_02
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK