Displaying IP addresses in Go using Stringer interface 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!

Example 1 with range.

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?
Your first variant is unnecessary detailed and hard to read:


an IPv4 address consists of exactly 4 digit groups
4 is a small number, maybe it's worth to inline the for loop
the for loop treats the case k == 0 specially
the += operator for strings allocates a new string each time
the code is much longer than the description in the task "join the four numbers with dots"


Your second variant is short, easy to grasp and probably efficient enough for all practical cases.

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


You can replace the %v with %d to make it more specific, since the arguments are integer values.

The main reason for choosing this variant is readability. The format string shows at a glance how the formatted string will look like.

If you want to write the fastest possible code, you should probably allocate a byte array of size 3+1+3+1+3+1+3 and append each number and dot individually, without using a loop at all.