Created
February 25, 2021 05:52
-
-
Save mr-pascal/165a79ddb1701e961006d1f414079344 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func writeCSVFile(persons []Person, outputPath string) { | |
// Define header row | |
headerRow := []string{ | |
"Firstname", "Lastname", "Country", | |
} | |
// Data array to write to CSV | |
data := [][]string{ | |
headerRow, | |
} | |
// Add persons to output data | |
for _, person := range persons { | |
data = append(data, []string{ | |
// Make sure the property order here matches | |
// the one from 'headerRow' !!! | |
person.Firstname, | |
person.Lastname, | |
person.Country, | |
}) | |
} | |
// Create file | |
file, err := os.Create(outputPath) | |
checkError("Cannot create file", err) | |
defer file.Close() | |
// Create writer | |
writer := csv.NewWriter(file) | |
defer writer.Flush() | |
// Write rows into file | |
for _, value := range data { | |
err = writer.Write(value) | |
checkError("Cannot write to file", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment