原文: https://spf13.com/post/go-pointers-vs-references/

Pointers Vs References

Some languages including C, C++ support pointers. Other languages including C++, Java, Python, Ruby, Perl and PHP all support references. On the surface both references and pointers are very similar, both are used to have one variable provide access to another. With both providing a lot of the same capabilities, it’s often unclear what is different between these different mechanisms. In this article I will illustrate the difference between pointers and references.

Why Does This Matter

Pointers are at the very core of effective Go. Most programmers are learning Go with a foundation in one of the languages mentioned above. Consequently understanding the difference between pointers and references is critical to understanding Go. Even if you are coming from a language that uses pointers, Go’s implementation of pointers differs from C and C++ in that it retains some of the nice properties of references while retaining the power of pointers.

The remainder of this article is written with the intent of speaking broadly about the concept of references rather than about a specific implementation. We will be using Go as the reference implementation for pointers.

What Is The Difference?

A pointer is a variable which stores the address of another variable.

A reference is a variable which refers to another variable.

To illustrate our point, use the following example in C++ which supports both pointers and references.

int i = 3;
int *ptr = &i;
int &ref = i;

The first line simply defines a variable. The second defines a pointer to that variable’s memory address. The third defines a reference to the first variable.

Not only are the operators different, but you use the differently as well. With pointers must use the * operator to dereference it. With a reference no operator is required. It is understood that you are intending to work with the referred variable.

Continuing with our example, the following two lines will both change the value of i to 13.

*ptr = 13;
ref = 13;

You may be asking, what happens if I try to access the ptr directly without dereferencing first. This takes us to our second critical difference between pointers and references. Pointers can be reassigned while references cannot. In other words, a pointer can be assigned to a different address.

Consider the following example in Go:

package main

import "fmt"

var ap *int

func main() {
a := 1 // define int
b := 2 // define int ap = &a
// set ap to address of a (&a)
// ap address: 0x2101f1018
// ap value : 1 *ap = 3
// change the value at address &a to 3
// ap address: 0x2101f1018
// ap value : 3 a = 4
// change the value of a to 4
// ap address: 0x2101f1018
// ap value : 4 ap = &b
// set ap to the address of b (&b)
// ap address: 0x2101f1020
// ap value : 2
}

So far you could do all of the above in a reasonably similar manner using references, and often with a simpler syntax.

Stay with me, the following example will illustrate why pointers are more powerful than references.

Extending the function above:

    ...

    ap2 := ap
// set ap2 to the address in ap
// ap address: 0x2101f1020
// ap value : 2
// ap2 address: 0x2101f1020
// ap2 value : 2 *ap = 5
// change the value at the address &b to 5
// ap address: 0x2101f1020
// ap value : 5
// ap2 address: 0x2101f1020
// ap2 value : 5
// If this was a reference ap & ap2 would now
// have different values ap = &a
// change ap to address of a (&a)
// ap address: 0x2101f1018
// ap value : 4
// ap2 address: 0x2101f1020
// ap2 value : 5
// Since we've changed the address of ap, it now
// has a different value then ap2
}

You can experiment and play yourself at go play: http://play.golang.org/p/XJtdLxFoeO

The key to understanding the difference is in the second example.

If we were working with references we would not be able to change the value of b through *ap and have that reflected in *ap2. This is because once you make a copy of a reference they are now independent. While they may be referring to the same variable, when you manipulate the reference it will change what it refers to, rather than the referring value.

The final example demonstrates the behavior when you change the assignment of one of the pointers to point to a new address. Due to the limitations of references this is the only operation available.

Stay tuned… Next post will feature another property exclusively available to pointers, the pointer pointer.

For more information on pointers I’ve found the following resources helpful

--------------------------------------------

golang 中引用和指针的区别

package main

import "fmt"

var ap *int

func main() {
a := 1 // define int
b := 2 // define int ap = &a
fmt.Println("set ap to address of a (&a)")
// ap address: 0x2101f1018
// ap value : 1
fmt.Println("ap address:", ap)
fmt.Println("ap value: ", *ap) *ap = 3
fmt.Println("change the value at address &a to 3")
// ap address: 0x2101f1018
// ap value : 3
fmt.Println("ap address:", ap)
fmt.Println("ap value: ", *ap) a = 4
fmt.Println("change the value of a to 4")
// ap address: 0x2101f1018
// ap value : 4
fmt.Println("ap address:", ap)
fmt.Println("ap value: ", *ap) ap = &b
fmt.Println("set ap to the address of b (&b)")
// ap address: 0x2101f1020
// ap value : 2
fmt.Println("ap address:", ap)
fmt.Println("ap value: ", *ap) ap2 := ap
fmt.Println("set ap2 to the address in ap")
// ap address: 0x2101f1020
// ap value : 2
// ap2 address: 0x2101f1020
// ap2 value : 2
fmt.Println("ap address: ", ap)
fmt.Println("ap value: ", *ap)
fmt.Println("ap2 address:", ap2)
fmt.Println("ap2 value: ", *ap2) *ap = 5
fmt.Println("change the value at the address &b to 5")
// ap address: 0x2101f1020
// ap value : 5
// ap2 address: 0x2101f1020
// ap2 value : 5
// If this was a reference ap & ap2 would now
// have different values
fmt.Println("ap address: ", ap)
fmt.Println("ap value: ", *ap)
fmt.Println("ap2 address:", ap2)
fmt.Println("ap2 value: ", *ap2) ap = &a
fmt.Println("change ap to address of a (&a)")
// ap address: 0x2101f1018
// ap value : 4
// ap2 address: 0x2101f1020
// ap2 value : 5
// Since we've changed the address of ap, it now
// has a different value then ap2
fmt.Println("ap address: ", ap)
fmt.Println("ap value: ", *ap)
fmt.Println("ap2 address:", ap2)
fmt.Println("ap2 value: ", *ap2)
}

  

golang 中Pointers Vs References的更多相关文章

  1. golang中的race检测

    golang中的race检测 由于golang中的go是非常方便的,加上函数又非常容易隐藏go. 所以很多时候,当我们写出一个程序的时候,我们并不知道这个程序在并发情况下会不会出现什么问题. 所以在本 ...

  2. 基础知识 - Golang 中的正则表达式

    ------------------------------------------------------------ Golang中的正则表达式 ------------------------- ...

  3. 在 VS 类库项目中 Add Service References 和 Add Web References 的区别

    原文:在 VS 类库项目中 Add Service References 和 Add Web References 的区别 出身问题: 1.在vs2005时代,Add Web Reference(添加 ...

  4. golang中的reflect包用法

    最近在写一个自动生成api文档的功能,用到了reflect包来给结构体赋值,给空数组新增一个元素,这样只要定义一个input结构体和一个output的结构体,并填写一些相关tag信息,就能使用程序来生 ...

  5. Golang中的坑二

    Golang中的坑二 for ...range 最近两周用Golang做项目,编写web服务,两周时间写了大概五千行代码(业务代码加单元测试用例代码).用Go的感觉很爽,编码效率高,运行效率也不错,用 ...

  6. Golang 中的坑 一

    Golang 中的坑 短变量声明  Short variable declarations 考虑如下代码: package main import ( "errors" " ...

  7. google的grpc在golang中的使用

    GRPC是google开源的一个高性能.跨语言的RPC框架,基于HTTP2协议,基于protobuf 3.x,基于Netty 4.x. 前面写过一篇golang标准库的rpc包的用法,这篇文章接着讲一 ...

  8. Golang中Struct与DB中表字段通过反射自动映射 - sqlmapper

    Golang中操作数据库已经有现成的库"database/sql"可以用,但是"database/sql"只提供了最基础的操作接口: 对数据库中一张表的增删改查 ...

  9. Golang中WaitGroup使用的一点坑

    Golang中WaitGroup使用的一点坑 Golang 中的 WaitGroup 一直是同步 goroutine 的推荐实践.自己用了两年多也没遇到过什么问题.直到一天午睡后,同事扔过来一段奇怪的 ...

随机推荐

  1. leetcode548 Split Array with Equal Sum

    思路: 使用哈希表降低复杂度.具体来说: 枚举j: 枚举i,如果sum[i - 1] == sum[j - 1] - sum[i],就用哈希表把sum[i - 1]记录下来: 枚举k,如果sum[k ...

  2. 【Matlab开发】matlab中bar绘图设置与各种距离度量

    [Matlab开发]matlab中bar绘图设置与各种距离度量 标签(空格分隔): [Matlab开发] [机器学习] 声明:引用请注明出处http://blog.csdn.net/lg1259156 ...

  3. 最新 唯品会java校招面经 (含整理过的面试题大全)

    从6月到10月,经过4个月努力和坚持,自己有幸拿到了网易雷火.京东.去哪儿.唯品会等10家互联网公司的校招Offer,因为某些自身原因最终选择了唯品会.6.7月主要是做系统复习.项目复盘.LeetCo ...

  4. 前端ajax中运用post请求和get请求之于session验证

    首先我们来看下ajax两种请求的区别: Ajax中POST和GET的区别Get和Post都是向服务器发送的一种请求,只是发送机制不同. 1. GET请求会将参数跟在URL后进行传递,而POST请求则是 ...

  5. noi openjudge7627:鸡蛋的硬度

    http://noi.openjudge.cn/ch0206/7627/ 描述 最近XX公司举办了一个奇怪的比赛:鸡蛋硬度之王争霸赛.参赛者是来自世界各地的母鸡,比赛的内容是看谁下的蛋最硬,更奇怪的是 ...

  6. 【转帖】龙芯将两款 CPU 核开源,这意味着什么?

    龙芯将两款 CPU 核开源,这意味着什么? https://www.oschina.net/news/78316/loongson-open-source-two-cpu-core 文章挺不错的 也讲 ...

  7. 使用window.open 实现弹框和居中对齐

    // 打开页面方法 window.open(url, '_blank', centerStyle('600', '400')+',toolbar=no,menubar=no,resizeable=no ...

  8. 【AtCoder】AGC033(A-F)

    AGC033 A - Darker and Darker 直接BFS #include <bits/stdc++.h> #define fi first #define se second ...

  9. java网络编程-面试题

    1.网络编程时的同步.异步.阻塞.非阻塞? 同步:函数调用在没得到结果之前,没有调用结果,不返回任何结果.异步:函数调用在没得到结果之前,没有调用结果,返回状态信息.阻塞:函数调用在没得到结果之前,当 ...

  10. Angular7如何动态刷新Echarts图表

    1 概述 echarts是百度的开源图表插件 Angular中引入echarts网上教程很多 Angular引入echarts,并使用动态刷新 2 安装 请参考大神的博客:https://blog.c ...