Golang Write New Column of CSV

I'm writing out two sets of data to one CSV in Go. Right now, using csv.NewWriter, I can write them to the same columns. This is not ideal, I would like them side-by-side, the second dataset in adjacent columns. Here's what I'm doing now:

    csvOut, _ := os.Create("Summary.csv")
    writer := csv.NewWriter(csvOut)

    for _, value := range dataset1 {
            writer.Write(value)
    }
    writer.Flush()
    for _, value := range dataset2 {
            writer.Write(value)
    }
    writer.Flush()

I know the normal writer has some offset options, does the csv writer have anything similar?


Solution 1:

Loop over the source data set records. Concatenate the records from each data set to create an output record. Write the output record to the file.

csvOut, _ := os.Create("Summary.csv")
writer := csv.NewWriter(csvOut)

var record []string  // declare record outside loop to reduce allocations
for i := range dataset1 {
        record = append(record[:0], dataset1[i]...) // copy data set 1 to beginning of output record
        record = append(record, dataset2[i]...) // append data set 2 to output record
        writer.Write(record)
}
writer.Flush()

This code assumes that len(dataset1) == len(dataset2). If this is not true, then modify the code per application requirements (add empty values, truncate to shorter dataset, ...)