I started to learn Go yesterday on the Tour of Go website and I thought that I was understanding everything well;
But then I was totally confused on the exercise Stringers: https://tour.golang.org/methods/18
So I searched a solution to see what I was doing wrong and I found this:
package main
import "fmt"
type IPAddr [4]byte
// TODO: Add a "String() string" method to IPAddr.
func (i IPAddr) String() string {
return fmt.Sprintf("%d.%d.%d.%d", i[0], i[1], i[2], i[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)
}
}
and the output is this:
loopback: 127.0.0.1
googleDNS: 8.8.8.8
it left me completely confused;
Why did the function activate itself? Should'nt it be like: i.String() inside the main func?
Why did the fmt.Printf show nothing on the screen at all?
Or the fmt.Printf returned that because the String() changed the value?
I'm sorry if the question is confusing, but can someone explain this to me?