I'm trying to write a CSV file using the package encoding/csv
. All data I want to write per line is saved in a struct like this:
type record struct {
Field0 string
Field1 string
Field2 string
Field3 string
}
The csv package has a method called Write that requires a slice of strings.
Is it possible to convert a struct to a slice of strings?
For example,
package main
import (
"fmt"
)
type record struct {
Field0 string
Field1 string
Field2 string
Field3 string
}
func main() {
r := record{"f0", "f1", "f2", "f3"}
fmt.Printf("%q
", r)
s := []string{
r.Field0,
r.Field1,
r.Field2,
r.Field3,
}
fmt.Printf("%q
", s)
}
Output:
{"f0" "f1" "f2" "f3"}
["f0" "f1" "f2" "f3"]
I find the https://github.com/fatih/structs package to be quite useful...
package main
import (
"fmt"
"github.com/fatih/structs"
)
type record struct {
Field0 string
Field1 string
Field2 string
Field3 string
}
func main() {
r := record{"f0", "f1", "f2", "f3"}
fmt.Printf("%q
", r)
s := structs.Names(r)
fmt.Printf("%q
", s)
}
Output:
{"f0" "f1" "f2" "f3"}
["f0" "f1" "f2" "f3"]