2

How can I create []string from struct's values in Go? For example, in the following struct:

type Person struct {
    Height    float64
    Weight    float64
    Name    string
    Born    string
}

Tim := Person{174.5, 68.3, "Tim", "United States"}

What I want to get is the following one:

[]string{"174.5", "68.3", "Tim", "United States"}

Since I want to save each record which is derived from the struct to a CSV file, and Write method of the *csv.Writer requires to take the data as []string, I have to convert such struct to []string.

Of course I can define a method on the struct and have it return []string, but I'd like to know a way to avoid calling every field (i.e. person.Height, person.Weight, person.Name...) since the actual data includes much more field.

Thanks.

1 Answer 1

3

There may be a simpler and/or more idiomatic way to do it, but what comes to mind for me is to use the reflect package like this:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    type Person struct {
        Height float64
        Weight float64
        Name   string
        Born   string
    }

    Tim := Person{174.5, 68.3, "Tim", "United States"}

    v := reflect.ValueOf(Tim)

    var ss []string
    for i := 0; i < v.NumField(); i++ {
        ss = append(ss, fmt.Sprintf("%v", v.Field(i).Interface()))
    }

    fmt.Println(ss)
}
Sign up to request clarification or add additional context in comments.

2 Comments

I was just reading the documentation of the package and trying to define a method, but couldn't succeed. Thanks a lot. The only reason you passed a pointer instead of a value to the reflect.ValueOf method is reflect.Elem() requires only interface or pointer, right?
@user2360798 Good question. I had overcomplicated that line; I've fixed it now: reflect.ValueOf(Tim) is sufficient.

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.