GoLang学习笔记(三十三)结构体中的方法及方法的继承和重写

Go语言同时有函数和方法,方法的本质是函数,但是方法和函数又具有不同点。
函数function是一段具有独立功能的代码,可以被重复多次调用,从而实现代码复用
方法method是一个类的行为功能,只有该类的对象才能调用。
Go语言的方法method是一种作用于特定类型变量的函数。这种特定类型的函数叫做Receiver(接收者、接收者、接收器)
接收者的概念类似于传动面向对象语言中的this或者self关键字。
Go语言的接收者强调了方法具有作用对象,而函数没有作用对象。
Go语言中,接收者的类型可以是任何类型,不仅仅是结构体,也可以是struct类型外的任何类型。
只要接收者不同,则方法名可以一样。
方法的语法格式:
func (接收者变量 接收者类型) 方法名(参数列表) (返回值列表){
    //方法体
}
接收者在func关键字和方法名之间编写,接收者可以是struct类型或非struct类型,可以是指针类型和非指针类型。
接收者中的变量在命名时,官方建议使用接收者类型的第一个小写字母。

type employee struct {
	name,currency string
	salary float64
}

func (e employee) printSalary() {
	fmt.Printf("姓名:%s , 薪资:%s %.2f  \n",e.name,e.currency,e.salary)
}

func testMethod01() {
	emp1 := employee{"Yoni","RMB",3000}
	emp1.printSalary()
}

用指针作为接收者

type rectangle struct {
	width,height float64
}

func (r rectangle) setValue() {
	r.height = 10
	r.width = 20
}

func (r *rectangle) setValue2() {
	r.height = 20
	r.width = 40
}

func testMethod02(){
	r1 :=rectangle{1,2}
	r2 := r1
	fmt.Printf("长:%f,高:%f \n",r1.width,r1.height)

	r1.setValue()
	fmt.Printf("R1修改后   r1长:%f,高:%f \n",r1.width,r1.height)
	fmt.Printf("R1修改后   r2长:%f,高:%f \n",r2.width,r2.height)

	r1.setValue2()
	fmt.Printf("R1修改后   r1长:%f,高:%f \n",r1.width,r1.height)
	fmt.Printf("R1修改后   r2长:%f,高:%f \n",r2.width,r2.height)
}

先写一个机构体及方法:

type human struct {
	name, phone string
	age         int8
}

type student struct {
	human
	school string
}

type employee struct {
	human
	company string
}

func (h human) sayHi() {
	fmt.Printf("我是%s,年龄%d,联系方式%s \n", h.name, h.age, h.phone)
}

方法的继承:

func testMethod11(){
	s1 := student{human{"s1","138001",13},"第一中学"}
	e1 := employee{human{"e1","138002",30},"第一企业"}
	s1.sayHi()    //我是s1,年龄13,联系方式138001
	e1.sayHi()    //我是e1,年龄30,联系方式138002
}

方法的重写:

func (s student) sayHi(){
	fmt.Printf("我是%s,年龄%d,我在%s上学,联系方式%s \n", s.name, s.age, s.school,s.phone)
}

func testMethod12(){
	s1 := student{human{"s1","138001",13},"第一中学"}
	s1.sayHi()    //我是s1,年龄13,我在第一中学上学,联系方式138001
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值