In Go, you can use the standard library package encoding/csv [docs] to write data to a CSV file. Below is a example that shows you how you can write a slice of user-data related strings to a CSV file.
The code creates a new file called users.csv and writes a slice of records to it. Finally, the Flush method is used to flush any buffered data to the underlying io.Writer, which is the file.
packagemainimport("encoding/csv""os""fmt")funcmain(){// Define the data
records:=[][]string{{"John","Doe","35"},{"Jane","Doe","29"},{"Jim","Smith","41"},}filename:="users.csv"// Write it to CSV
err:=WriteToCsv(records,filename)iferr!=nil{panic(err)}fmt.Println("Created file:",filename)}// WriteToCsv accepts a slice of strings to write to a csv file.
funcWriteToCsv(records[][]string,filenamestring)error{file,err:=os.Create(filename)iferr!=nil{returnerr}deferfile.Close()writer:=csv.NewWriter(file)deferwriter.Flush()for_,record:=rangerecords{err:=writer.Write(record)iferr!=nil{returnerr}}returnnil}
Running this code should output the name of the file it’s just created. In our example, we also check for errors, but we just use a panic() - you are going to want to improve on this by handling the error appropriately.
Edd is a PHP and Go developer who enjoys blogging about his experiences, mostly about creating and coding new things he's working on and is a big beliver in open-source and Linux.