从Golang Struct生成Serializer

时间:2018-02-16 10:27:20

标签: go struct

我有这样的结构,

type Example struct{
    a int
    b int
    c string
}

func Calculate(){
    obj := Example{1,2,"lahmacun"}
    // do something in here
    // I have to get this result as a string: "[a=1,b=2,c=lahmacun]"
    // Example can be anything. which means we dont know anything about struct. Just we know its a struct.
}

我想制作一个序列化器,但我无法制作它。

注意:在nodejs中,我们有... in循环。这很容易。但在golang,一切都与我截然不同。

1 个答案:

答案 0 :(得分:0)

我找到了答案。感谢@mkopriva< 3

func PKIStringify(v interface{}) (res string) {
    rv := reflect.ValueOf(v)
    num := rv.NumField()
    for i := 0; i < num; i++ {
        fv := rv.Field(i)
        st := rv.Type().Field(i)
        fmt.Println(fv.Kind())
        res += st.Name + "="
        switch fv.Kind() {
        case reflect.String:
            res += fv.String()
        case reflect.Int:
            res += fmt.Sprint(fv.Int())
        case reflect.Struct:
            res += PKIStringify(fv.Interface())
        }
        if i != num-1 {
            res += ","
        }
    }

    return "[" + res + "]"
}