为什么指向 int 的指针用“*int”而不是“int”初始化?

Why is a pointer to int initialised with “*int” and not “&int”?

例如,当初始化一个指向int的指针时,我们使用:

var pointer *int

为什么不是语法:

var pointer &int

对我来说,第二个版本会更有意义,因为它看起来像“变量‘指针’是一个 int 的内存地址”

或者换句话说,我发现“*”同时用于定义内存地址类型(如上所述)和取消引用,例如 *指针 = 123

这是不是看起来很混乱,还是我漏掉了什么?

& 是一个 address operator,不是一个类型。

For an operand x of type T, the address operation &x generates a pointer of type *T to x.

但确实如此*也被用作指针间接:

For an operand x of pointer type *T, the pointer indirection *x denotes the variable of type T pointed to by x

Tour of Go 中所示,* 引用类型和运算符。

这个 thread from 2016 问了一个类似的问题。

The pointer syntax is just copied from C, of course.
See also Go's Declaration Syntax
If we had used '&', then a Go pointer would look like a C++ reference.

并且:

*int defines a pointer type and then can be used with or without the * on the variable.

  • With the * you access the value pointed to.
  • Without, you access the memory address pointed to.

& retrieves a memory address from a variable.

An address is not a pointer and vice versa.
You define a pointer using a memory address.

var x int = 10    // declare an int variable `x` holding the value 10.
var y *int = &x  // Create a pointer `y` *using* the memory address of `x`.

*y will have the value 10.
y will be the memory address of x


更多见“Pointers in Go" from Dave Cheney:

Go pointers, like C pointers, are values that, uh, point to other values. This is a tremendously important concept and shouldn’t be considered dangerous or something to get hung up on.

A pointer is a value that points to the memory address of another variable.

但是:

you cannot alter the address p points to unless you assign another address to it
No: var p *int; p++ possible.

(另见“Go at Google: Language Design in the Service of Software Engineering”)

Once a value is assigned to a pointer, with the exception of nil, Go guarantees that the thing being pointed to will continue to be valid for the lifetime of the pointer.