dspld86684 2017-09-25 05:20
浏览 59
已采纳

遍历go结构以获得csv字符串[重复]

This question already has an answer here:

I have a struct representing a dataset that I need to write to a CSV file as a time-series data. This is what I have so far.

type DataFields struct {
    Field1 int,
    Field2 string,
    ...
    Fieldn int
}

func (d DataFields) String() string {
    return fmt.Sprintf("%v,%v,...,%v", Field1, Field2,..., Fieldn)
}

Is there a way I can iterate through the members of the struct and construct a string object using it?

Performance is not really an issue here and I was wondering if there was a way I could generate the string without having to modify the String() function if the structure changed in the future.

EDITED to add my change below:

This is what I ended up with after looking at the answers below.

func (d DataFields) String() string {
    v := reflect.ValueOf(d)
    var csvString string
    for i := 0; i < v.NumField(); i++ {
        csvString = fmt.Sprintf("%v%v,", csvString, v.Field(i).Interface())
    }

    return csvString
}
</div>
  • 写回答

3条回答 默认 最新

  • douren2831 2017-09-25 06:58
    关注

    What you are looking for is called reflection. This answer explains how to use it to loop though a struct and get the values.

    This is the example the author uses on the other answer:

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func main() {
        x := struct{Foo string; Bar int }{"foo", 2}
        v := reflect.ValueOf(x)
        values := make([]interface{}, v.NumField())
    
        for i := 0; i < v.NumField(); i++ {
            values[i] = v.Field(i).Interface()
        }
    
        fmt.Println(values)
    }
    

    You can see it working on the go playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?