分享
  1. 首页
  2. 文章

MAY-Lesson2

夜空一起砍猩猩 · · 1358 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:夜空一起砍猩猩

查看原文:MAY-Lesson2

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
1358 次点击
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏