1. 结构体和方法之间
方法接收器是结构体的值与指针中的区别:
package main
import "fmt"
type Person struct {
Name string
Age int
}
func (this Person) Call() {
fmt.Println("啊啊啊")
}
func (this *Person) Touch() {
fmt.Println("痒痒痒")
}
func main() {
person := Person{
Name: "董小贱",
Age: 18,
}
person.Call()
person.Touch()
}
thisselfthisthisthis
package main
import "fmt"
type Person struct {
Name string
Age int
}
func (this Person) Call() {
this.Name = "dong"
fmt.Println("啊啊啊")
}
func (this *Person) Touch() {
this.Name = "xiaojian"
fmt.Println("痒痒痒")
}
func main() {
person := Person{
Name: "董小贱",
Age: 18,
}
fmt.Println(person) //{董小贱 18}
person.Call() // 啊啊啊
fmt.Println(person) // {董小贱 18}
person.Touch() // 痒痒痒
fmt.Println(person) //{xiaojian 18}
}
TouchNameCallNameCallName
Touch(&person).Touch()person.Touch()
personCallthisTouchthispersonTouchthis
以上不是本笔记的重点,以下才是...
2 . 结构体、方法和接口之间的千丝万缕
先看一段代码:
package main
import "fmt"
type sportsMan interface {
Run()
Jump()
}
type runner interface {
Run()
}
type highJumper interface {
Jump()
}
type Person struct {
Name string
Age int
}
func (this Person) Run() {
fmt.Println("跑跑跑")
}
func (this *Person) Jump() {
fmt.Println("跳跳跳")
}
func main(){
person := Person{
Name:"董小贱",
Age:18,
}
person.Run()
person.Jump()
runner := runner(person)
runner.Run()
highjumper := highJumper(person)
highjumper.Jump()
}
cannot convert person (type Person) to type highJumper:Person does not implement highJumper (Jump method has pointer receiver)&personPersonhighJumper
方法集
变量类型 | 方法接收器类型 |
---|---|
T | (t T) |
*T | (t T) && (t *T) |
T类型的值得方法集只包含值接收声明的方法。指向T类型的指针方法集即包含值接受者声明的方法,也包含指针接收者声明的方法
方法接收器类型 | 变量类型 |
---|---|
(t T) | T && *T |
(t *T) | *T |
如果使用指针接收器来实现一个接口,那么只有指向那个类型的指针才能够实现对应的接口。 如果使用值接收器来实现一个接口,那么这个类型的值和指针都能实现对应的接口。
说了这么多,还是拿代码说事:
package main
import "fmt"
type sportsMan interface {
Run()
Jump()
}
type runner interface {
Run()
}
type highJumper interface {
Jump()
}
type Person struct {
Name string
Age int
}
func (this Person) Run() {
fmt.Println("跑跑跑")
}
func (this *Person) Jump() {
fmt.Println("跳跳跳")
}
func main(){
person := Person{
Name:"董小贱",
Age:18,
}
person.Run()
person.Jump()
runner := runner(person)
runner.Run()
highjumper := highJumper(&person)
highjumper.Jump()
sportsman := sportsMan(&person)
sportsman.Jump()
sportsman.Run()
}
highJumper&personrunner
sportsMan
接口中方法是值类型接收器,随便传; 接口中方法是指针类型接收器,只能传指针类型;接口中方法中的接收器类型都有,为了都满足也只能传指针类型。
接口中方法的值类型接收器,传入的是指针类型,在方法中操作结构体的字段的指也不会改变全局的结构体的值。