Search⌘ K

Solution 2: Reflection and Interfaces

Explore how to use reflection and interfaces in Go for dynamic typing and sorting of CSV data. Learn to read different CSV formats, implement sorting methods, and enhance functionality by adding reverse order capabilities.

Problem 1: Solution

Here is the integration of the functionality of sortCSV.go in phonebook.go.

Mihalis,Tsoukalos,210,9416471,1609310706
Dimitris,Tsoukalos,210,9416871,1609310731
Mihalis,Tsoukalos,210,9416571,1609310717
Dimitris,Tsoukalos,210,9416971,1609310734
Jane,Doe,0800,123456,1609310777
phoneBook.go

Code explanation

The code reads data from a CSV file, either in Format 1 or Format 2. Format 1 has four fields (name, surname, telephone, last access date), and Format 2 has five fields (name, surname, area code, telephone, last access date). The program determines the format of the file by looking at the number of fields in the first line.

The data is read from the file and stored in a slice of structures (Book1 or Book2, depending on the format of the file). The program then sorts the data by certain fields and displays the results.

  • Lines 12–26: Define the struct types F1 and F2 for the two formats of the CSV file.

  • Lines 28–29: ...