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
", 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?