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 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥15 pip install后修改模块路径,import失败,需要在哪里修改环境变量?
  • ¥15 爬取1-112页所有帖子的标题但是12页后要登录后才能 我使用selenium模拟登录 账号密码输入后 会报错 不知道怎么弄了
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决