在 interface{} 的位置传递结构时出错

所以,我有这样的功能


func ProcessRequest(requestBody *SignInRequest, response func(SignInResponse) *src.Response, error func(ControllerError) *src.Response) *src.Response {

    return error(ControllerError{Code: http.StatusNotImplemented})

}

而我试图称之为


ProcessRequest(payload, myFunction, handler.OnControllerError)



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


}

这向我显示了一个错误


不能使用 'myFunction' (type func(i interface{}) *src.Response) 作为类型 func(SignInResponse) *src.Response


但是如果我尝试同样的事情


type TestStruct struct {

    

}


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


}


myFunction2(TestStruct{})

然后它没有显示任何错误。


我希望它interface{}作为一个论点,因为我想myFucntion成为可以接受任何struct.


开心每一天1111
浏览 72回答 1
1回答

饮歌长啸

你混淆了两件事。当你有一个带有 signaure 的函数时func (interface{}) *src.Response,你确实可以在传递任何类型的值的同时调用它,但事实并非如此。发生的情况是您有另一个函数 ,ProcessRequest并且其参数的类型之一是类型为 的函数func (SignInResponse) *src.Response。当您尝试将类型值传递给func (interface{}) *src.Response接受类型参数的函数时会发生错误,func (SignInResponse) *src.Response因为这些参数的类型显然不兼容。更新。要了解为什么参数的类型不兼容,请考虑SignInResponse并interface{}在内存中具有不同的存储表示;基本上这就是为什么[]T和[]interface{}不兼容的原因,即使你可以做到t := T{}; var i interface{} = t。常见问题解答中对此进行了解释。至于手头的问题,据说最简单的方法是使用匿名函数将值“调整”SignInResponse为interface{}:传递给类似的ProcessResponse东西func (r SignInResponse) *src.Response {    return myFunction2(r)}
打开App,查看更多内容
随时随地看视频慕课网APP