How to print out pointer variable correctly in golang

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

How to print out pointer variable correctly in golang

问题

type person struct{}
var tom *person = &person{}

当我使用

fmt.Printf("%+v\n", tom)//打印结果:&{}

为什么结果是&加上数据?它应该是一个地址(0x0055)

当我使用

fmt.Printf("%+v\n", &tom)//0x0038
fmt.Printf("%p\n", &tom)//0x0038

它给我一个地址,它给我0x0038,为什么%v和%p有相同的结果?

英文:
type person struct{}
var tom *person = &person{}

How to print out pointer variable correctly in golang

When I use

fmt.Printf("%+v\n", tom)//prints:&{}

Why the result is & plus data?It is surposed to be an address(0x0055)

When I use

fmt.Printf("%+v\n", &tom)//0x0038
fmt.Printf("%p\n", &tom)//0x0038

It gives me an address,it gives me 0x0038,why %v and %p has the same result?

答案1

得分: 4

tom是一个指向person的指针。当你使用&tom时,你创建了一个第二个指针,这是一个指向指针的指针。

在你的第一个例子中,你使用%+v来打印tom的默认值。默认值解引用指针并打印结构体本身。

在你的第二个例子中,%+v应用于"double"指针。它仍然解引用指针,获取到初始指针。请参考这个例子:http://play.golang.org/p/IZThhkiQXM

英文:

tom is a pointer to a person. When you use &tom, you're a creating a second pointer, this a pointer to a pointer to a person.

In your first example, you're using %+v to print the default value of tom. The default value deferences the pointer and prints the struct itself.

In your second example, %+v is applying to the "double" pointer. It still deferences the pointer, getting to the initial pointer. See this example: http://play.golang.org/p/IZThhkiQXM

huangapple
  • 本文由 发表于 2014年4月17日 23:50:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/23137757.html
匿名

发表评论

匿名网友

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

确定