I have a struct like this,
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.
}
I want to make a serializer but i could not make it.
Note : In nodejs we have for...in loop. It was very easy. But in golang everything very different to me.
I found a answer. Thanks to @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 + "]"
}