Go中指针绑定函数和值绑定函数的区别

本文阐述,go语法中,指针绑定函数和 值绑定函数的区别和表现

首先先定义一个struct,然后定义两个方法,一个用pointer 绑定,一个用value绑定

type StructA struct {
  name string
}

func(a *StructA) sayHelloPoint()  {
	a.name="helloPoint"
}

func (a StructA) sayHelloNoPoint()  {
	a.name="helloNopoint"
}



首先看到用普通 value绑定的值,通过指针和value都可调用,然后看其的值表现的区别

type StructA struct {
  name string
}

func(a *StructA) sayHelloPoint()  {
	a.name="helloPoint"
}

func (a StructA) sayHelloNoPoint()  {
	a.name="helloNopoint"
}




func main() {

	var a, b StructA
	fmt.Println(a)
	a.sayHelloPoint("sayHelloPoint with value")
	fmt.Println(a)

	(&a).sayHelloPoint("sayHelloPoint with pointer")
	fmt.Println(a)

	b.sayHelloNoPoint("sayHelloNoPoint with value")
	fmt.Println(b)

	(&b).sayHelloNoPoint("sayHelloNoPoint with point")
	fmt.Println(b)

}

输出:

{}
{sayHelloPoint with value}
{sayHelloPoint with pointer}
{}
{}

解析,通过默认值 StructA 调用方法,struct的默认值不为nil可以直接调用函数,  可以看到 不管是通过 value 绑定函数,还是通过pointer绑定函数,其调用都是可以通过双边调用来调用的,而不用管其调用形式,

定义为pointer 绑定函数的,能明显看到,里面的name 被改变了,而通过value绑定函数的,里面的name 没有改变,其通过pointer调用也一样,这种两种形式的相互调用(可以看做编译器为我们写法方便,自动帮我们做了转换)

上述调用可以转换一下,写法,使其看起来更清晰一点,为啥通过pointer绑定函数可以改变value,而通过value绑定函数改变不了值

扫描二维码关注公众号,回复: 11347491 查看本文章
type StructA struct {
  name string
}

func(a *StructA) sayHelloPoint()  {
	a.name="helloPoint"
}

func (a StructA) sayHelloNoPoint()  {
	a.name="helloNopoint"
}




func main() {

	fun1 :=StructA.sayHelloNoPoint
	a:=StructA{}
	fun1(a,"value bind func")
	//fun1(&a,"hello") 编译不通过
	fmt.Println(a)

	fun2:=(*StructA).sayHelloPoint
	b:=StructA{}
	//fun2(b,"hello") 编译不通过
	fun2(&b,"hello")
	fmt.Println(b)


}

其输出为:

{}
{hello}

解析,可以看到通过pointer绑定函数的行为,可以看做,函数执行时候传参 struct的指针,此时可以改变其内部的name变量,而通过value绑定的函数,函数执行传参的时候,传的是值的拷贝,自然改变不了内部的值。

猜你喜欢

转载自blog.csdn.net/dongjijiaoxiangqu/article/details/106896763