Blaszard
Blaszard

Reputation: 31955

How to create []string from struct in Go

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.

Upvotes: 2

Views: 620

Answers (1)

Darshan Rivka Whittle
Darshan Rivka Whittle

Reputation: 34031

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)
}

Upvotes: 3

Related Questions