[英]Go receiver implicit pointer conversion not working
I'm learning Go, and I was following the go tour. 我正在学习Go,我正在跟随之旅。
In the exercise about Stringer, here , Implementing the function with a *IPAddr receiver doesn't seem to work, which the go tour describes as should work. 在关于Stringer的练习中, 在这里 ,使用* IPAddr接收器实现该功能似乎不起作用,go tour描述为应该工作。
package main
import "fmt"
type IPAddr [4]byte
// TODO: Add a "String() string" method to IPAddr.
func (ip *IPAddr) String() string {
return fmt.Sprintf("%v.%v.%v.%v", ip[0], ip[1], ip[2], ip[3])
}
func main() {
hosts := map[string]IPAddr{
"loopback": {127, 0, 0, 1},
"googleDNS": {8, 8, 8, 8},
}
for name, ip := range hosts {
fmt.Printf("%v: %v\n", name, ip)
}
}
Output is: 输出是:
loopback: [127 0 0 1]
googleDNS: [8 8 8 8]
But changing String() string
to func (ip IPAddr)
from func (ip *IPAddr)
gives the correct output: 但是从
func (ip *IPAddr)
将String() string
更改为func (ip IPAddr)
func (ip *IPAddr)
会得到正确的输出:
loopback: 127.0.0.1
googleDNS: 8.8.8.8
Why is that? 这是为什么?
Implementing func (ip IPAddr) String()
will work for both IPAddr
and *IPAddr
types. 实现
func (ip IPAddr) String()
将适用于IPAddr
和*IPAddr
类型。
Implementing func (ip *IPAddr) String
will only work for *IPAddr
. 实现
func (ip *IPAddr) String
仅适用于*IPAddr
。
The implicit conversion means that you can call the function on either a value, or pointer, but it does not satisfy the implementation of an interface. 隐式转换意味着您可以在值或指针上调用该函数,但它不满足接口的实现。 If you implement an interface with a pointer receiver, the pointer must be used in the function call.
如果使用指针接收器实现接口,则必须在函数调用中使用指针。
The code below shows the *IPAddr
used with the Stringer interface, and an IPAddr
used with the new foo()
function (also implemented with a pointer receiver): 下面的代码显示了与Stringer接口
*IPAddr
使用的*IPAddr
,以及与新的foo()
函数IPAddr
使用的IPAddr
(也使用指针接收器实现):
package main
import "fmt"
type IPAddr [4]byte
// TODO: Add a "String() string" method to IPAddr.
func (ip *IPAddr) String() string {
return fmt.Sprintf("%v.%v.%v.%v", ip[0], ip[1], ip[2], ip[3])
}
func (ip *IPAddr) foo() string {
return "bar"
}
func main() {
hosts := map[string]IPAddr{
"loopback": {127, 0, 0, 1},
"googleDNS": {8, 8, 8, 8},
}
for name, ip := range hosts {
fmt.Printf("%v: %v\n", name, &ip)
fmt.Println(ip.foo())
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.