There are times, mostly for logging and debugging, when you have a slice of a given type that you would like to print to a log file or just convert to a CSV of values.
A quick and easy way to convert a slice to a CSV in Golang is to use the json
module to Marshal
it a JSON
encoded array
.
package main
import (
"encoding/json"
"fmt"
)
func main() {
ints := []int64{1, 2, 3, 4}
intsCSV, _ := json.Marshal(ints)
fmt.Printf("ints = %s\n", intsCSV)
floats := []float64{3.14, 6.47}
floatsCSV, _ := json.Marshal(floats)
fmt.Printf("floats = %s\n", floatsCSV)
}