Solution 2: Composite Data Types
Let’s solve the challenges set in the previous lesson.
Problem 1: Solution
Here's the updated code that separates the fields of a record based on the # character:
Code explanation
- Line 49: Here, - csvwriter.Comma = '#', the default field delimiter for the CSV data, is changed from a comma (- ,) to a hash (- #) symbol. This change will ensure that each field of a record in the CSV file is separated by a- #symbol.
- Line 51: - temp := []string{row.Name, row.Surname, row.Number, row.LastAccess}creates an array of strings- temp, which stores the values of the fields of a record. This line ensures that the fields of a record are separated by a- #symbol when written to the CSV file.
- Line 74: - line := strings.Split(line, "#")splits the fields of a record in the input CSV file based on the- #symbol. This line ensures that the fields of a record are properly separated and stored in the line array.
Following is the output of the code above:
# cat csv.dataDimitris#Tsoukalos#2101112223#1600665563Mihalis#Tsoukalos#2109416471#1600665563Jane#Doe#0800123456#1608559903# go run csvData.go csv.data output.data{Dimitris Tsoukalos 2101112223 1600665563}{Mihalis Tsoukalos 2109416471 1600665563}{Jane Doe 0800123456 1608559903}# cat output.dataDimitris#Tsoukalos#2101112223#1600665563Mihalis#Tsoukalos#2109416471#1600665563Jane#Doe#0800123456#1608559903
Problem 2: Solution
Here’s a sample implementation in Go ...