如何打印整个url.URL结构?

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

How do I print the entire url.URL struct?

问题

我有以下的代码 https://play.golang.org/p/utnlHJqlX1:

package main

import (
    "fmt"
    "net/url"
)

func main() {
    u, err := url.Parse("http://www.something.com")
    if err != nil {
        fmt.Println(err)
    }

    fmt.Printf("%+v", u)
}

我期望"%+v"打印出结构体和字段,但实际上它打印出了"http://www.something.com"。

英文:

I have the following https://play.golang.org/p/utnlHJqlX1:

package main

import (
	"fmt"
	"net/url"
)

func main() {
	u, err := url.Parse("http://www.something.com")
	if err != nil {
		fmt.Println(err)
	}

	fmt.Printf("%+v", u)
}

I was expecting the "%+v" to print the struct and the fields. Instead it prints: "http://www.something.com"

答案1

得分: 5

似乎是因为Parse返回了指向结构体的指针。

请尝试使用以下代码(注意*):

fmt.Printf("%+v\n", *u)

修改后的 playground:

https://play.golang.org/p/Grjrp2QriK

编辑

进一步解释一下,之所以会这样,是因为在使用%+v时,fmt对实现了Stringer接口的结构体有不同的处理方式。

这是相关的代码:https://golang.org/src/fmt/print.go?s=4772:4849#L577

由于*URL实现了Stringer接口:https://golang.org/pkg/net/url/#URL.String

这就是使用的字符串。

通过解引用指针,我们得到一个URL,它不实现该接口(因为String方法中的接收者是一个指针)。

英文:

It seems to be because Parse is returning a pointer to the struct.

Try with this (note the *):

fmt.Printf("%+v\n", *u)

Modified playground:

https://play.golang.org/p/Grjrp2QriK

EDIT

To expand on this, the reason for this is that fmt treats structs that implement Stringer differently when doing %+v.

This is the relevant code: https://golang.org/src/fmt/print.go?s=4772:4849#L577

Since *URL implements Stringer: https://golang.org/pkg/net/url/#URL.String

That's the string being used.

By dereferencing the pointer, we get an URL, which does not implement the interface (cause the receiver in the String method is a pointer).

答案2

得分: 0

你可以始终使用%#v格式化动词来打印任何值的Go语法表示。例如:

fmt.Printf("%#v\n", u)

这对于调试和自动生成代码非常方便。由于输出是Go表示形式,因此可以将其粘贴到测试或类似的地方作为变量。

这样,你就不需要担心覆盖fmt.Stringer的类型了。

英文:

You can always use the %#v formatting verb to print the Go syntax representation for any value. For example:

fmt.Printf("%#v\n",u)

This can be handy for debugging & automatic code generation. Since the output is the Go representation, this could be pasted into a test or similar as a variable.

This way you don't need to worry about type that override fmt.Stringer

huangapple
  • 本文由 发表于 2017年7月24日 08:17:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/45271052.html
匿名

发表评论

匿名网友

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

确定