英文:
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{}

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


评论