doushi2902 2017-04-16 13:21
浏览 15
已采纳

在Go中将结构的字段和不同类型的值写入文件

I'm writing a simple program that takes in input from a form, populates an instance of a struct with the received data and the writes this received data to a file.

I'm a bit stuck at the moment with figuring out the best way to iterate over the populated struct and write its contents to the file.

The struct in question contains 3 different types of fields (ints, strings, []strings).

I can iterate over them but I am unable to get their actual type.

Inspecting my posted code below with print statements reveals that each of their types is coming back as structs rather than the aforementioned string, int etc.

The desired output format is be plain text.

For example:

field_1="value_1"
field_2=10
field_3=["a", "b", "c"]

Anyone have any ideas? Perhaps I'm going about this the wrong way entirely?

func (c *Config) writeConfigToFile(file *os.File) {

    listVal := reflect.ValueOf(c)
    element := listVal.Elem()

    for i := 0; i < element.NumField(); i++ {
        field := element.Field(i)
        myType := reflect.TypeOf(field)

        if myType.Kind() == reflect.Int {
            file.Write(field.Bytes())
            } else {
                file.WriteString(field.String())
            }
        }
}
  • 写回答

2条回答 默认 最新

  • douju6752 2017-04-16 14:28
    关注

    Instead of using the Bytes method on reflect.Value which does not work as you initially intended, you can use either the strconv package or the fmt to format you fields.

    Here's an example using fmt:

    var s string
    switch fi.Kind() {
    case reflect.String:
        s = fmt.Sprintf("%q", fi.String())
    case reflect.Int:
        s = fmt.Sprintf("%d", fi.Int())
    case reflect.Slice:
        if fi.Type().Elem().Kind() != reflect.String {
            continue
        }
    
        s = "["
        for j := 0; j < fi.Len(); j++ {
            s = fmt.Sprintf("%s%q, ", s, fi.Index(i).String()) 
        }
        s = strings.TrimRight(s, ", ") + "]"
    default:
        continue
    }
    
    sf := rv.Type().Field(i)
    if _, err := fmt.Fprintf(file, "%s=%s
    ", sf.Name, s); err!= nil {
        panic(err)
    }
    

    Playground: https://play.golang.org/p/KQF3CicVzA

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

报告相同问题?

悬赏问题

  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件