chapter three

3 A bookworm’s digest: playing with loops and maps

 

This chapter covers

  • Ranging over slice and map
  • Using a map to store unique values
  • Learning how to open and read a file
  • Decoding JSON file
  • Sorting a slice with custom comparators

Since the invention of writing, people have been using the tool to carve their thoughts through the centuries. Books were knowledge and became a hobby. We have been reading and collecting them on shelves. With technology, we are now able to share information more than ever, and give our opinion on everything, including books. In this chapter, we’ll join a group of bookworms who have been reading books. Fadi and Peggy have started registering the books they keep on their bookshelves, and they wonder if we can help them find books they both have read, and, maybe, suggest future reads.

In this chapter, we will reinforce what we learned about command line interfaces in chapter 2 by creating a book digest from bookworms’ book collections. Step by step, from a list of books per reader, we will build a program returning and printing the books found on more than one shelf. As a bonus, we will practise map and slice ranging to create a tool recommending books. The input of our executable is a JSON file, and we can learn how to read a file in Go and how to parse a JSON using the standard libraries from Go. For the sake of simplicity here, we will assume that each book has only one author. How ironic it is, you will say.

Requirements

3.1 Load the JSON data

3.1.1 Define a JSON example

3.1.2 Open a file

3.1.3 Parse the JSON

3.1.4 Test it

3.2 Find common books

3.2.1 Count the books

3.2.2 Keep higher occurrences

3.2.3 Determinism

3.3 Print

3.4 Improvements

3.4.1 Exercise: reading recommendations

3.4.2 Implement sort.Interface

3.4.3 Use bufio to open a file

3.5 Summary