MAY-Lesson2

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,499评论 0 10
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,026评论 0 38
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,129评论 0 23
  • 重要的不是你最终到达哪个位置,而是无论停在哪个位置,你都将因为无与伦比的经历而成为无与伦比的你。 ——何袜皮《我走...
    2c255455eca1阅读 328评论 0 2
  • 风儿吹着泛黄的树叶, 沙沙的响声在我脑中回响, 让我于这个烦躁的季节更加心神不安。 桌边的书被风吹开了几页, 这风...
    季紫清阅读 270评论 0 2