为什么& (地址)阵列打印“&”进去 [英] why does & (address) of an array print "&" in go
问题描述
这里是代码
Here is the go code
package main
func main() {
var ax [2]int
ax[0] = 22
ax[1] = 99
bx := ax
cx := &ax
fmt.Println(ax)
fmt.Println(bx)
fmt.Println(cx)
fmt.Printf("%p\n", cx)
}
当我执行它时,我以下输出
When I execute it, it gives me the following output
PS C:\personal\gospace> ./bin/test
[22 99]
[22 99]
&[22 99]
0xc0420381d0
cx:=& ax
正确地将cx解释为指针。但是当我打印cx时,它会打印& [22 99]
,当我打印& ax [0]
或
cx := &ax
rightly interpreted cx as pointer. But when I print cx it prints &[22 99]
and when I print &ax[0]
or %p
formatter for cx it rightly prints the address. Why is this behavior?
推荐答案
默认打印动词 fmt.Println
是%v
。在打印区分值与指针值时,这就是为什么在 cx
前面看到&
。
Default printing verb fmt.Println
uses is %v
. While printing it differentiates value vs pointer value, that's why you see &
in front of cx
.
fmt.Println(cx)
接下来, fmt.Printf
使用动词%p
,请参阅 printing 部分,它会打印基准16表示法,并带有前导的0x
。
Next, you specifically tell fmt.Printf
to use the verb %p
, refer to printing section and it prints base 16 notation, with leading 0x
.
fmt.Printf("%p\n", cx)
这篇关于为什么& (地址)阵列打印“&”进去的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!