-2

I have two function in my code, a parent function with interface{} parameter type and another child function with interface{} parameter type. I called childFunc in parentFunc and assert parent param to *interface{} and pass it to childFunc and at the end i called parent function with &user argument

func childFunc(param interface{}){}

func parentFunc(param interface{}){
     childFunc(*(param.(*interface{})))
}

parentFunc(&user)

but i have this error:

interface conversion: interface {} is *models.User, not *interface {}

what is the problem? how can i solve this problem?

this is my real code.

func Update(context echo.Context, modelUpdatedInstance interface{}, constraints map[string]interface{}) error {

    /* Validation */
    //test := modelUpdatedInstance.(*interface{})
    _, validationErrors := govalidator.ValidateStruct(*(modelUpdatedInstance.(*interface{})))
    if validationErrors != nil {
        return validation.CheckValidation(context, validationErrors)
    }

    if constraints != nil {
        database.DB.First(modelUpdatedInstance, constraints["id"]).Model(modelUpdatedInstance).Updates(modelUpdatedInstance)
    } else {
        return context.JSON(http.StatusBadRequest, map[string]interface{}{"Errors": []string{"no identifier"}})
    }

    return context.JSON(http.StatusOK, *(modelUpdatedInstance.(*interface{})))
}

1 Answers1

0

The govalidator.ValidateStruct function expects a pointer to a struct. The top caller has a pointer to a struct.

Simply pass the pointer through the calls.

func top() {
    childFunc(&user{})
}

func parentFunc(param interface{}) {
    childFunc(param)
}

func childFunc(param interface{}) {
    _, err := govalidator.ValidateStruct(param)
    ...
}

Run it on the playground.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
  • i mean the question in this page: https://stackoverflow.com/questions/49540367/how-do-i-dereference-a-pointer-value-passed-as-the-empty-interface sorry for misleading you – Bahman Binary Jul 26 '20 at 19:48
  • is there any solution for that other than `reflect` – Bahman Binary Jul 26 '20 at 19:51
  • @BahmanBinary It's unclear how `reflect` or the linked question relates to the question. It looks like you are attempting to dereference pointers where you should use the pointer value. Remove the attempts to dereference the pointers from the code (including the type assertion) and try that. Report back with what does not work. – Charlie Tumahai Jul 26 '20 at 20:10