为什么& (地址)阵列打印“&”进去 [英] why does & (address) of an array print "&" in go

查看:145
本文介绍了为什么& (地址)阵列打印“&”进去的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是代码

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] %p 格式化程序可以正确打印地址。为什么会出现这种行为?

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆