Home > front end >  Error while passing struct in the place of interface{}
Error while passing struct in the place of interface{}

Time:02-14

So, I have a function like this

func ProcessRequest(requestBody *SignInRequest, response func(SignInResponse) *src.Response, error func(ControllerError) *src.Response) *src.Response {
    return error(ControllerError{Code: http.StatusNotImplemented})
}

And I'm trying to call this

ProcessRequest(payload, myFunction, handler.OnControllerError)


func myFunction(i interface{}) *src.Response {

}

This is showing me an error

Cannot use 'myFunction' (type func(i interface{}) *src.Response) as the type func(SignInResponse) *src.Response

But if I try the same thing with

type TestStruct struct {
    
}

func myFunction2(i interface{}) *src.Response {

}

myFunction2(TestStruct{})

Then it is not showing any error.

I want it to take interface{} as an argument because I want myFucntion to be general which can take any struct.

CodePudding user response:

You're confusing two things.

When you have a function with the signaure func (interface{}) *src.Response, you indeed can call it while passing it a value of any type, but that is not what happens.

What happens is that you have another function, ProcessRequest, and one of the types of its arguments is a function with the type func (SignInResponse) *src.Response.
The error happens when you try to pass a value of type func (interface{}) *src.Response to a function which accepts an argument of type func (SignInResponse) *src.Response because the types of these arguments are obviously not compatible.

Update.
To understand why the types of the arguments are not compatible, consider that SignInResponse and interface{} have different storage representation in memory; basically that's the same reason why []T and []interface{} are not compatible even when you can do t := T{}; var i interface{} = t. This one is explained in the FAQ.

As to the problem at hand, supposedly the easiest approach is to use an anonymous function to "adapt" the value SignInResponse to interface{}: pass to ProcessResponse something like

func (r SignInResponse) *src.Response {
    return myFunction2(r)
}
  •  Tags:  
  • go
  • Related