Learning Golang, Day 11 – I Solved the Stringers Exercise!

Learning Golang, Day 11 – I Solved the Stringers Exercise!

Here we are on day 11, where I solved the Stringers Exercise.


Well, while I did implement the solution today, it was yesterday when I felt that I was on the right track, encouraged by Peter Hellberg in the #newbies channel of gophers.slack.com. Thanks, Peter!

If you’ve not read the problem definition, it’s:

Make the IPAddr type implement fmt.Stringer to print the address as a dotted quad. For instance, IPAddr{1, 2, 3, 4} should print as "1.2.3.4".

Here’s my solution, which uses a combination of the append() function, fmt.Sprintf(), and strings.Join().

package main

import (
	"fmt"
	"strings"
)

type IPAddr [4]byte

func (ipa IPAddr) String() string {
	var output []string
	for _, v := range ipa {
		output = append(output, fmt.Sprintf("%d", v))
	}

	return strings.Join(output, ".")
}

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

I had a good think about several, possible ways that I could approach this, but kept thinking that Go had to have something analogous to PHP’s implode() method. If you’re not familiar with implode, it joins the elements of an array together with a given string. So, the following example, would print out: James, Jodie, Matthew, Michael.

<?php

echo implode(
    ", ",
    ["James", "Jodie", "Matthew", "Michael"]
);

After a bit of searching, I came across the strings.Join() method. However, I couldn’t pass a byte array to the function, as it accepts an array of strings. Given that, I used a loop, the append() function, and fmt.Sprintf() to create a string array from the original byte array. Then, once created, used strings.Join() to create a string where each element in the array was joined together by a dot/period.

As I mentioned yesterday, the thing that was tripping me up was my lack of appreciation of the byte type. Quoting zetcode:

A byte in Go is an unsigned 8-bit integer. It has type uint8. A byte has a limit of 0 – 255 in numerical range. It can represent an ASCII character.

Given that knowledge I used %d with fmt.Sprintf() to format each byte as a base-10 integer and return its string equivalent. I don’t know if it’s the best solution, but it’s succinct and clear (to me). How would you have implemented String()?

Share your thoughts in the comments, and see you, next time!


You might also be interested in these tutorials too...


Want more tutorials like this?

If so, enter your email address in the field below and click subscribe.

You can unsubscribe at any time by clicking the link in the footer of the emails you'll receive. Here's my privacy policy, if you'd like to know more. I use Mailchimp to send emails. You can learn more about their privacy practices here.

Join the discussion

comments powered by Disqus