指针!对的,你没有看错,Golang居然有指针,C++转过来的人笑了。

值传递

func Update(value int) {
	value=value+1
}

func main() {
	value:=1
	Update(value)
	fmt.Println("当前值:",value)
}
-----------------------------------
当前值: 1

value的值并没有变,还是1,因为函数传进去值的副本。

使用指针作为参数

func Update(value *int) {
	*value=*value+1
}

func main() {
	value:=1
	Update(&value)
	fmt.Println("当前值:",value)
}
------------------------------------
当前值: 2

value的值变为了2,和C++里面指针是一样的。

结构体使用指针

type Param struct {
	Value int
}
func (this Param) Add() {
	this.Value++
}
func main() {
	p:=&Param{Value:1}
	p.Add()
	fmt.Println("Value的值:",p.Value)
}
--------------------------------------------
Value的值: 1
type Param struct {
	Value int
}
func (this *Param) Add() {
	this.Value++
}
func main() {
	p:=&Param{Value:1}
	p.Add()
	fmt.Println("Value的值:",p.Value)
}
--------------------------------------------
Value的值: 2

看到上面的区别了吗?一个是输出的 1,一个是输出的2,区别就在于第二个例子使用了(this *Param)

go随聊-指针

 

相关文章: