Working with Two Different CSV File Formats

Let’s learn how to work with two different CSV file formats.

In this lesson, we are going to implement a separate command-line utility that works with two different CSV formats. The reason we are doing this is that there are times when we will need our utilities to be able to work with multiple data formats.

Remember that the records of each CSV format are stored using their own Go structure under a different variable name. As a result, we need to implement sort.Interface for both CSV formats and, therefore, for both slice variables.

The two supported file formats

The two supported formats are the following:

  • Format 1: Name, surname, telephone number, time of last access

  • Format 2: Name, surname, area code, telephone number, time of last access

As the two CSV formats that are going to be used have a different number of fields, the utility determines the format that is being used by the number of fields found in the first record that was read and acts accordingly. After that, the data will be sorted using sort.Sort()—the data type of the slice that keeps the data helps Go determine the sort implementation that is going to be used without any help from the developer.

Note: The main benefit we get from functions that work with empty interface variables is that we can add support for additional data types easily at a later time without the need to implement additional functions and without breaking existing code.

Implementation details

What follows is the implementation of the most important functions of the utility beginning with readCSVFile() because the logic of the utility is found in the readCSVFile() function.

Get hands-on with 1200+ tech skills courses.