【golang】小笔记-要点tips-持续更新中

1、接口、接收者调用者、值类型指针类型

Demo 1

当接收者为值类型时,无论调用者是值类型还是指针类型,接收者的更改都不会影响调用者。

当接收者是指针类型时,无论调用者是值类型还是指针类型,接收者的更改均会影响调用者。


type Person struct {
	Name string
	Age int
}

func (p Person) GetName() string {
	return p.Name
}
func (p Person) SetName(name string) {
	p.Name = name
}

func (p *Person) GetAge() int {
	return p.Age
}
func (p *Person) SetAge(age int) {
	p.Age = age
}

func TestF(test *testing.T)  {
	Luffy := Person{
		Name: "luffy",
		Age: 21,
	}
	Sanji := &Person{
		Name: "sanji",
		Age: 23,
	}
	fmt.Printf("My name is %s, I'm %d years old \n", Luffy.Name, Luffy.Age)
	fmt.Printf("My name is %s, I'm %d years old \n", Sanji.Name, Sanji.Age)
	fmt.Println(".................3 years later ......................")
	Luffy.SetName("luffy3")
	Luffy.SetAge(Luffy.Age + 3)
	Sanji.SetName("sanji3")
	Sanji.SetAge(Sanji.Age + 3)
	fmt.Printf("My name is %s, I'm %d years old \n", Luffy.GetName(), Luffy.GetAge())
	fmt.Printf("My name is %s, I'm %d years old \n", Sanji.GetName(), Sanji.GetAge())
}

打印结果

My name is luffy, I'm 21 years old
My name is sanji, I'm 23 years old
.................3 years later ......................
My name is luffy, I'm 24 years old
My name is sanji, I'm 26 years old

总结:

Demo2

 

type PersonInterface interface {
	SayHi()
}

type Man struct {}

type Woman struct {}

func (m Man) SayHi() {
	fmt.Println("I'm a man")
}

func (w *Woman) SayHi() {
	fmt.Println("I'm a woman")
}

func TestF(test *testing.T)  {
	var man PersonInterface = Man{}
	man.SayHi()
	var ptrMan PersonInterface = &Man{}
	ptrMan.SayHi()

	var woman PersonInterface = Woman{} //这里报错,错误提示见下面贴图
	woman.SayHi()

	var ptrWoman PersonInterface = &Woman{}
	ptrWoman.SayHi()
}

总结:实现了接收者是值类型的方法,相当于自动实现了接收者是指针类型的方法;而实现了接收者是指针类型的方法,不会自动生成对应接收者是值类型的方法。【https://qcrao91.gitbook.io/go/interface/zhi-jie-shou-zhe-he-zhi-zhen-jie-shou-zhe-de-qu-bie

推荐阅读:https://www.infoq.cn/article/wDURRBz1Nv3IbIeviIJF

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值