问题描述
Go的新手,所以请忍受我.
New to Go, so please bear with me.
我一直在浏览去旅行"页面,偶然发现一些关于斯金格斯的困惑.在 https://tour.golang.org/methods/18
I've been looking at the "Tour of Go" pages, and stumbled into something puzzling about Stringers. Consider the exercise at https://tour.golang.org/methods/18
我最初的答案是实施
func (this *IPAddr) String() string {
return fmt.Sprintf("%d.%d.%d.%d", this[0], this[1], this[2], this[3])
}
但是,仅用于fmt.Printf("%v: %v\n", name, ip)
的主要打印内容不使用此功能.如果我将打印内容更改为fmt.Printf("%v: %v\n", name, ip.String())
,则无论接收器类型是*IPAddr
还是IPAddr
,都将使用它.
however, this is not used f main prints just fmt.Printf("%v: %v\n", name, ip)
. If I change the print to fmt.Printf("%v: %v\n", name, ip.String())
, then it is used whether the receiver type is *IPAddr
or IPAddr
).
为什么会这样?
推荐答案
由于要向fmt.Printf
传递IPAddr
值,因此String()
方法不属于方法集.如果传递指针,您的解决方案将起作用:
Because you're passing an IPAddr
value to fmt.Printf
, your String()
method isn't part of the method set. Your solution works if you pass in a pointer:
fmt.Printf("%v: %v\n", name, &ip)
但是一般的解决方案是不使用指针接收器:
But a general solution is to not use a pointer receiver:
func (ip IPAddr) String() string {
return fmt.Sprintf("%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3])
}
这样,可以从要传递给Printf
的IPAddr
或包括值接收器的方法的*IPAddr
中使用String()
方法.
This way the String()
method can be used from an IPAddr
, which is what you're passing to Printf
, or an *IPAddr
, which includes the methods of the value receiver.
这篇关于斯金格斯的困惑行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!