I've been attempting to figure out how to properly write a map to a csv file with no luck.
I essentially have a program that queries an sql database, I store one of the return values as the key to the map, and then a slice of string for the data related to it that's returned, as an example the map would be:
var m = make(map[string][]string)
m['test1'] = [5, 4, 3]
so writing it to a csv would be
test1, 5, 4, 3
Its printed to the csv just like a list/slice would be, I'm storing it in a map to make it easier to construct dynamic queries elsewhere.
I've attempted using a for loop such that:
for key, value := range m{
writer.Write(key)
writer.Write(value)
}
but I'm getting the following error:
cannot use key (type string) as type []string in argument to writer.Write
I've done a lot of googling and searching here and can't seem to find a way to do this properly.
Package csv
func (*Writer) Write
func (w *Writer) Write(record []string) error
Writer writes a single CSV record to w along with any necessary quoting. A record is a slice of strings with each string being one field.
error: cannot use key (type
string
) as type[]string
in argument towriter.Write
"I've done a lot of googling and searching here."
To solve this problem, read the documentation of Write
and follow the instructions in the error message, You have type string
, Write
wants type []string
. For example,
for key, value := range m {
r := make([]string, 0, 1+len(value))
r = append(r, key)
r = append(r, value...)
err := writer.Write(r)
if err != nil {
// handle error
}
}
writer.Flush()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With