所以,我有这样的功能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.
1 回答
饮歌长啸
TA贡献1951条经验 获得超3个赞
你混淆了两件事。
当你有一个带有 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)
}
- 1 回答
- 0 关注
- 71 浏览
添加回答
举报
0/150
提交
取消