Reputation: 391
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?
Upvotes: 2
Views: 8961
Reputation: 31
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\n", r)
vals := structs.Values(r)
fmt.Printf("%q\n", vals)
}
Output:
{"f0" "f1" "f2" "f3"}
["f0" "f1" "f2" "f3"]
Upvotes: 3
Reputation: 166855
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\n", r)
s := []string{
r.Field0,
r.Field1,
r.Field2,
r.Field3,
}
fmt.Printf("%q\n", s)
}
Output:
{"f0" "f1" "f2" "f3"}
["f0" "f1" "f2" "f3"]
Upvotes: 3