How to write struct to csv?

I have a struct consisting of a series of strings.
I wish to write the struct values to file using the csv package like so.

From what I can gather 
``` writer.Write()
takes a slice.
My question is what is the correct/best/idiomatic way to move the contents of the struct into a slice, or is there a different/better/easier approach to achieve this?

start here: https://godoc.org/github.com/fatih/structs#Values

package main

 import (
    "fmt"

    "github.com/fatih/structs"
)

func main() {
    data := struct {
	    First  string
	    Second string
	    Third  string
    }{
	    "hello",
	    "out",
	    "there",
    }

    s := make([]string, 0)
    for _, v := range structs.Values(data) {
	    s = append(s, v.(string))
    }
    fmt.Printf("%#v\n", s)
 }
1 Like

For a fixed, known struct, the straightforward and type-safe way is to write a struct method that turns each field into a string and returns a slice of these strings that a csv.Writer will accept.

If you want to write a generic function that can convert all kinds of structs into a slice of strings, then you need to use reflection - see @clbanning’s answer.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.