2

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?

2 Answers 2

3

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"]
Sign up to request clarification or add additional context in comments.

Comments

3

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"]

1 Comment

Output is actually a slice of fields, not values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.