I'm learning Go, and I was following the go tour.
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.
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:
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.
Implementing func (ip *IPAddr) String
will only work for *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):
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())
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.