How to solve a task with fmt.Stringer?

How to solve a this task with fmt.Stringer?

Maybe, my decision is not the best:

package main

import "fmt"

type IPAddr [4]byte

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.%v.%v.%v\n", name, ip[0], ip[1], ip[2], ip[3])
	}
}

output:

loopback: 127.0.0.1
googleDNS: 8.8.8.8

It asked you to implent a Stringer interface, but you instead change the print statement. I believe that is not what the go Tour asks you to do.

In that and the question, how to do it?

func (ip IPAddr) String() string {
	return fmt.Sprintf("%d.%d.%d.%d",ip[0],ip[1],ip[2],ip[3])
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.