Pointers in Go

Source:
(1)Pointers in Go
(2)Understand Go pointers in less than 800 words or your money back
(3)Pointers vs. Values

Digest:
1. Pointers in Go:
Go pointers, like C pointers, are values that, uh, point to other values.
Here are several ways that Go improves over C pointers, and C++, for that matter.
(1) There is no pointer arithmetic. You cannot write in Go

var p *int
p++

That is, you cannot alter the address p points to unless you assign another address to it.
(2) This means there is no pointer/array duality in Go.
(3) Once a value is assigned to a pointer, with the exception of nil which i'll cover in the next point, Go guarantees that the thing being pointed to will continue to be valid for the lifetime of the pointer. So

func f() *int {
	i := 1
	return &i
}

is totally safe to do in Go. The compiler will arrange for the memory location holding the value of i to be valid after f() returns.
(4) Nil pointers. Yes, you can still have nil pointers and panics because of them, however in my experience the general level of hysteria generated by nil pointer errors, and the amount of defensive programming present in other language like Java is not present is Go.
I believe this is for three reasons:
(a) multiple return values, nil is not used as a sentinel for something went wrong. Obviously this leaves the question of programmers not checking their errors, but this is simply a matter of education.
(b) Strings are value types, not pointers, which is the, IMO, the number one cause of null pointer exceptions in language like Java and C++.

var s string // the zero value of s is "", not nil.

(c) In fact, most of the built in data types, maps, slices, channels, and arrays, have a sensible default if they are left uninitialized.
2. What is memory?
Computer memory, RAM, can be thought of as a sequence of boxes, placed one after another in a line. Each box, or cell, is labeled with a unique number, which increments sequentially; this is the address of the cell, its memory location.
Each cell holds a single value. If you know the memory address of a cell, you can go to that cell and read its contents. You can place a value in that cell; replacing anything that was in there previously.
That's all there is to know about memory. Everything the CPU does is expressed as fetching and depositing values into memory cell.
3. What is a variable?
To write a program that retrieves the value stored in memory location 200, multiples it by 3 and deposits the result into memory location 201, we could write something like this in pseudocode:
(1) retrieve the value stored in address 200 and place it in the CPU.
(2) multiple the value stored in the CPU by 3.
(3) deposit the value stored in the CPU into memory location 201.
This is exactly how early programs were written; programmers would keep a list of memory locations, who used it, when, and what the value stored there represented.
Obviously this was tedious and error prone, and meant every possible value stored in memory had to be assigned an address during the construction of the program. Worse, this arrangement made it difficult to allocate storage to variables dynamically as the program ran -- just imagine if you had to write large programs using only global variables.
To address this, the notion of a variable was created. A variable is just a convenient, alphanumeric pseudonym for a memory location; a label, or nickname.
Now, rather than talking about memory locations, we can talk about variables, which are convenient names we give to memory locations. The previous program can now be expressed as:
(1) Retrieve the value stored in variable a and place it in the CPU.
(2) multiple it by 3.
(3) deposit the value into the variable b.
This is the same program, with one crucial improvement -- because we no longer need to talk about memory locations directly, we no longer need to keep track of them -- that drudgery is left to the compiler.
Now we can write a program like:

var a = 6
var b = a * 3

And the compiler will make sure that the variables a and b are assigned unique memory locations to hold their value for as long as needed.
4. What is a pointer?
Now that we know that memory is just a series of numbered cells, and variables are just nicknames for a memory location assigned by the compiler, what is a pointer?
A pointer is a value that points to the memory address of another variable.
The pointer points to memory address of a variable, just as a variable represents the memory address of value.
Let's have a look at this program fragment:

func main() {
	a := 200
	b := &a
	*b++
	fmt.Println(a)
}

On the first line of main we declare a new variable a and assign it the value 200.
Next we declare a variable b and assign it the address a. Remember that we don't know the exact memory location where a is stored, but we can still store a's address in b.
The third line is probably the most confusing, because of the strongly typed nature of Go. b contains the address of variable a, but we want to increment the value stored in a. To do this we must dereference b, follow the pointer from b to a.
Then we add one the value, and store it back in the memory location stored in b.
The final line prints the value of a, showing that it has increased to 201.

5. Pointers vs. Values:
The rule about pointers vs. values for receivers is that value methods can be invoked on pointers and values, but pointer methods can only be invoked on pointers.
This rule arises because pointer methods can modify the receiver; invoking them on a value would cause the method to receive a copy of the value, so any modifications would be discarded.
There is a handy exception, though. When the value is addressable, the language takes care of the common case of invoking a pointer method on a value by inserting the address operator automatically.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值