为什么在Go语言中,数组的地址打印出来会显示”&”符号?

huangapple go评论64阅读模式
英文:

why does & (address) of an array print "&" in go

问题

以下是翻译好的内容:

这是Go代码:

package main

import "fmt"

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)

}

当我执行它时,它给出以下输出:

PS C:\personal\gospace> ./bin/test
[22 99]
[22 99]
&[22 99]
0xc0420381d0

cx := &ax 正确地将 cx 解释为指针。但是当我打印 cx 时,它打印出 &[22 99],而当我打印 &ax[0] 或使用 %p 格式化符号打印 cx 时,它正确地打印出地址。为什么会出现这种行为?

英文:

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 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?

答案1

得分: 7

默认的打印动词fmt.Println使用的是%v。当打印时,它会区分值和指针值,这就是为什么你在cx前面看到&的原因。

fmt.Println(cx)

接下来,你明确告诉fmt.Printf使用动词%p,参考打印部分,它会以0x开头的十六进制表示法进行打印。

fmt.Printf("%p\n", 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)

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)

huangapple
  • 本文由 发表于 2017年6月20日 07:56:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/44641643.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定