John Smith
John Smith

Reputation: 391

Convert struct to slice of strings?

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

Answers (2)

Chris Gabel
Chris Gabel

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

peterSO
peterSO

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

Related Questions