英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论