Exercise 2: Reflection and Interfaces

Let’s test our understanding by attempting these challenges.

We'll cover the following

The following questions are to let you practice what you’ve learned. For further guidance, you can see a full solution to the problems in the next lesson.

Problem 1

The sortCSV.go code, provided in the playground below, is a Go program that reads data from a CSV file specified as a command-line argument. The CSV file may contain data in two possible formats, Format 1 and Format 2. The program reads the file, determines the format based on the number of columns in the first line, and then stores the data in either a Book1 or Book2 slice, depending on the format. The program provides sorting functionality for both types of data based on specific sorting criteria. The program’s main function reads the CSV file, performs the necessary checks and operations, and finally calls the sorting function for the appropriate data type.

Now, you need to integrate the functionality of sortCSV.go in phonebook.go, that is:

  1. Add the ability to import data in Format 2. The format of the input data may be detected based on the number of fields in each record.

  2. Add the ability to sort data based on different rules for different formats: data in Format 1 is to be sorted by surname and then name, while data in Format 2 is to be sorted by area code and then surname.

  3. Enhance the list() function to display data in Format 2.

Get hands-on with 1200+ tech skills courses.