I am trying out some Go code examples (while coding a private project) to get more "in-depth" knowledge about the language.
I have come across an exercise from the Go Tour website about displaying correctly an IP number, making use of type method and the Stringer interface.
I found two ways to achieve the goal but I am wondering if there is no other clean way of doing it.
I strongly believe that a method with fewer code lines is always better - even though, looking around some Go OpenSource projects differs from that!
package main
import "fmt"
type IPAddr [4]byte
// TODO: Add a "String() string" method to IPAddr.
func (ip IPAddr) String() string {
rs := ""
for k, v := range ip {
if k == 0 {
rs += fmt.Sprintf("%v", v)
continue
}
rs += fmt.Sprintf(".%v", v)
}
return rs
}
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)
}
}
Example 2 with a simple fmt.Sprintf
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)
}
}
What do you guys suggest?