I'm trying to compare 2 struct at run time. I can't seem to compare the field one by one. I'm thinking i would need to cast the type for each field while running my loop but reflect.TypeOf()
doesn't give me expected result of "type" ( int / string in that case ). I'm thinking it's because i'm providing an interface{} as an argument? is there any way to make it work ?
My goal is to be able to compare value from 2 structs of the same type and " merge " the values into one struct if there's any differences.
package main
import (
"fmt"
"reflect"
)
type A struct {
Foo string
Bar int
Zoo int
}
func main() {
a := &A{Foo: "qwer",Bar:1}
b := &A{Foo: "zxcv",Bar:1}
testRefactor(a,b)
}
func testRefactor(t *A,comp *A) {
valt := reflect.ValueOf(t).Elem()
//valComp := reflect.ValueOf(comp).Elem()
for i:=0; i<valt.NumField();i++{
//fieldStructComp := valComp.Type().Field(i).Name
fieldStructT := valt.Type().Field(i).Name
valueStructComp := getFieldValueByname(comp,fieldStructT)
valueStructT := getFieldValueByname(t,fieldStructT)
typex := reflect.TypeOf(valueStructT)
fmt.Println(typex.String())
fmt.Println(valueStructT)
fmt.Println(valueStructComp)
fmt.Println(valueStructT == valueStructComp)
}
}
func getFieldValueByname(structName interface{},fieldname string) interface{} {
r := reflect.ValueOf(structName)
f := reflect.Indirect(r).FieldByName(fieldname)
return f
}
Aucun commentaire:
Enregistrer un commentaire