golang pointer
We can find that, by changing the parameter to a pointer type, the passed pointer argument &a and its copy x used in the function body both reference the same value, so the modification on *x is equivalent to a modification on *p, a.k.a., variable a. In other words, the modification in the double function body can be reflected out of the function now.Surely, the modification of the copy of the passed pointer argument itself still can't be reflected on the passed pointer argument. After the second double function call, the local pointer p doesn't get modified to nil.In short, pointers provide indirect ways to access some values. Many languages have not the pointer concept. However, pointers are just hidden under other concepts in those languages.
我们可以发现,通过将参数更改为指针类型,传递的指针参数&a及其x在函数体中使用的副本都引用相同的值,因此修改 *x等效于修改 *p,aka,variable a。换句话说,double函数体中的修改现在可以从函数中反映出来。当然,传递的指针参数本身的副本的修改不能反映在传递的指针参数上。在第二个double函数调用之后,本地指针 p不会被修改为nil。简而言之,指针提供了访问某些值的间接方法。许多语言都没有指针概念。但是,指针只是隐藏在这些语言中的其他概念之下。
https://play.golang.org/p/6uGfdqOqQPL
package main
import "fmt"
func double(x *int) {
fmt.Println("address of x in method(double): ", &x) // 0x40c130, 0x40c140
fmt.Println("value of x in method(double): ", x) // 0x414020, 0x414020
fmt.Println("value of *x in method(double): ", *x) //3 , 6
*x += *x
x = nil // the line is just for explanation purpose
}
func main() {
var a = 3
fmt.Println("address of var a :", &a) // 0x414020
double(&a)
fmt.Println(a) // 6
p := &a
fmt.Println("value of p : ", p) // 0x414020
fmt.Println("address of p : ", &p) //0x40c138
double(p)
fmt.Println(a, p == nil) // 12 false
}
输出
address of var a : 0x414020
address of x in method(double): 0x40c130
value of x in method(double): 0x414020
value of *x in method(double): 3
6
value of p : 0x414020
address of p : 0x40c138
address of x in method(double): 0x40c140
value of x in method(double): 0x414020
value of *x in method(double): 6
12 false
有疑问加站长微信联系(非本文作者)