doushi2902 2017-04-16 05: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 06: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部