zero value of a pointer with %v and %p in Golang

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

zero value of a pointer with %v and %p in Golang

问题

我对指针的%p和%v格式化动词提供的输出感到困惑。

var a *int
// a的零值为:
fmt.Printf("%v", a) // <nil>
// 使用%p
fmt.Printf("%p", a) // 0x0

我们知道%v默认使用%p作为格式化器,那么为什么%v的输出是<nil>呢?

未初始化指针的零值是<nil>,那么为什么%p输出的是0x0而不是<nil>呢?

根据Go文档,%p使用带有前导0x的16进制表示法,那么<nil>0x0是相同的吗?

英文:

I am confusing the outputs provided by %p and %v format verbs of a pointer

var a *int
// zero value of a is:
fmt.Printf(&quot;%v&quot;, a) // &lt;nil&gt;
// using %p 
fmt.Printf(&quot;%p&quot;, a) // 0x0

We know that %v uses %p as the default formatter, then why %v showing &lt;nil&gt; as output?

The zero value of an uninitialized pointer is &lt;nil&gt;, then why %p outputting 0x0 instead <nil>?

As per Go docs, %p uses base 16 notation with leading 0x, if so, is &lt;nil&gt; and 0x0 are same?

答案1

得分: 4

  1. v是通用的值动词,它将空指针打印为&lt;nil&gt;,因为这在通用格式化中是最合理的。请注意其描述中的“默认”一词:它将p作为默认值,而不是无条件地使用。

  2. p打印指针值,因此将空指针打印为0x0。请注意,pv是不同的动词。

  3. 是的,空指针是0。但请注意,字符串&lt;nil&gt;0x0并不是“相同的”。

(提示:试图通过聪明地使用fmt.Printf来学习东西是非常困难的,因为它包含了很多(合理的)魔法。)

英文:
  1. v is the generic value verb and it prints nil pointers as &lt;nil&gt; because that makes most sense as a generic formatting. Note the word "default" in its description: It uses p as default, not unconditionally.

  2. p prints pointer values and thus prints a nil pointer as 0x0. Note that p and v are different verbs.

  3. Yes, nil pointers are 0. But note that the strings &lt;nil&gt; and 0x0 are not "the same".

(Tip: It is incredibly hard to learn things by trying to be clever with fmt.Printf as it contains a lot of (sensible) magic.)

huangapple
  • 本文由 发表于 2022年1月11日 02:59:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/70657603.html
匿名

发表评论

匿名网友

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

确定