mercredi 25 juillet 2018

How to compare data using Reflection between struct and map[string]interface{} in Golang

I am trying to compare these two interfaces together as a function. It is working as far as I am concerned. I am sending a struct in A interface{} and map[string]interface{} in B, having the same values but when being compared with reflect they are not resulting to be the same. I would like to be able to convert the map[string]interface{} into a struct interface inside this function so that my tests can get shorter. I have tried using https://github.com/mitchellh/copystructure, but does not work inside this function.(from outside it works though:

var m map[string]interface{}
var something StructType
err := mapstructure.Decode(m, &something)

if err.... and then i send the something in the B interface)

below is the function to compare the interfaces

func CompareData(Ainterface{}, B interface{}, t *testing.T) {
    a := reflect.ValueOf(A)
    b := reflect.ValueOf(B)
    akind := a.Kind().String()
    bkind := a.Kind().String()
    if akind == "slice" && bkind == "slice" {
        for i := 0; i < a.Len(); i++ {
            log.Println("they are sliced")
            CompareData(a.Index(i).Interface(), b.Index(i).Interface(),t)
            log.Println("\n", a.Index(i).Interface(), "\n", b.Index(i).Interface())
        }
        t.Fatal("this is a slice you need to iterate over the values")
    } else {
        log.Println("\n\n", A, "\n", B)
        if !reflect.DeepEqual(a.Interface(), b.Interface()) {
            t.Fatal("These should be equal\nSuccessData:\t", a.Interface(), "\nData:\t\t", b.Interface())
        }
        log.Println("\nA:\t", A, "\nB:\t", B)
    }
}





Aucun commentaire:

Enregistrer un commentaire