pointers - fmt.Printf() 格式说明符以默认格式打印指向结构的指针?

标签 pointers go struct format-specifiers

我的 Go 代码:

package main

import (
    "fmt"
)

type Point struct {
    x int
    y int
}

func main() {
    fmt.Println(&Point{1, 2})
    fmt.Printf("%v\n", &Point{1, 2})
    fmt.Printf("%p\n", &Point{1, 2})
}

输出:

&{1 2}
&{1 2}
0xc00002c070

这与 https://godoc.org/fmt 中的文档不匹配.文档说,

The default format for %v is:

bool:                    %t
int, int8 etc.:          %d
uint, uint8 etc.:        %d, %#x if printed with %#v
float32, complex64, etc: %g
string:                  %s
chan:                    %p
pointer:                 %p

根据上面的文档,对于指针,使用 %v 应该像使用 %p 一样。

为什么 fmt.Printf("%v\n", &Point{1, 2}) 的输出与 fmt.Printf("%p\n", &Point{1, 2})?

最佳答案

您引用了 fmt 的部分内容包装文档,只是“不够”。你的报价的延续:

For compound objects, the elements are printed using these rules, recursively, laid out like this:

struct:             {field0 field1 ...}
array, slice:       [elem0 elem1 ...]
maps:               map[key1:value1 key2:value2 ...]
pointer to above:   &{}, &[], &map[]

*Point 是指向结构的指针,因此使用 &{field0 field1 ...} 打印。

指向结构的指针在 Go 中很常见,并且大多数时候在打印它时您对指针值不感兴趣,而是对指向的结构(或指向的结构的字段)感兴趣。所以 fmt 包有一个规则来打印最想看到的内容。如果您确实需要该地址,您可以像示例中那样使用 %p 打印它。

关于pointers - fmt.Printf() 格式说明符以默认格式打印指向结构的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63337411/

相关文章:

c++ - 从结构启动 Cuda Call

c - 在 C 编程中将枚举指针传递给参数

c - C 中的数组地址减法

c - 访问返回指针时出现段错误

c - realloc() 第一次调用后不分配

xml - golang XML 不解码

golang 比较两个结构及其接口(interface)参数

go - time.Now() 和 time.Now().Local() 有什么区别?

c - 返回指向结构数组的指针

c++ - 在另一个文件中引用 C++ 结构对象?