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