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.


:idseparator: - :idprefix: :experimental: :source-highlighter: rouge :rouge-style: pastie :imagesdir: /images

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 https://gophers.slack.com[gophers.slack.com]. Thanks, Peter!

If you’ve not read https://go.dev/tour/methods/18[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().

[source,go]

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 https://www.php.net/manual/en/function.implode.php[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.

[source,php]

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 https://gobyexample.com/string-formatting[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, link:/learning-golang/day-12[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