2

I'm trying to complete this exercise in the Tour of Go, https://tour.golang.org/methods/18, to implement a String() method for an IPAddr type consisting of an array of four bytes. So far I've tried:

package main

import (
    "fmt"
    "strings"
)

type IPAddr [4]byte

func (ipaddr IPAddr) String() string {
    ipaddrStrings := make([]string, 4)
    for i, b := range ipaddr {
        ipaddrStrings[i] = string(b)
    }
    return strings.Join(ipaddrStrings, ".")
}

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)
    }
}

However, this prints

loopback: ...
googleDNS:.

I've also tried, following https://programming.guide/go/convert-byte-slice-to-string.html, to do string(ipaddr), but this results in a

cannot convert ipaddr (type IPAddr) to type string

How can I complete this exercise?

1
  • string(ipaddr[:]) seems to just return an empty string. Also, according to en.wikipedia.org/wiki/IP_address#IPv4_addresses, an IPv4 address consists of 32 bits or 4 bytes, so I believe the problem is stated realistically. Commented Sep 15, 2019 at 18:28

3 Answers 3

5

Add this method:

func (a IPAddr) String() string {
    return fmt.Sprintf("%d.%d.%d.%d", a[0], a[1], a[2], a[3])
}
Sign up to request clarification or add additional context in comments.

Comments

3

Instead of string(b), try strconv.Itoa(int(b)) to convert the numeric value to a string.

Comments

2

Independently, I came up with the same solution as outlined by bserdar:

package main

import (
    "fmt"
    "strconv"
    "strings"
)

type IPAddr [4]byte

func (ipaddr IPAddr) String() string {
    ipaddrStrings := make([]string, 4)
    for i, b := range ipaddr {
        ipaddrStrings[i] = strconv.Itoa(int(b))
    }
    return strings.Join(ipaddrStrings, ".")
}

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)
    }

}

This prints:

loopback: 127.0.0.1
googleDNS: 8.8.8.8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.