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

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口