登录
首页 >  Golang >  Go问答

出错在传递结构时的接口位置

来源:stackoverflow

时间:2024-02-19 08:39:22 438浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《出错在传递结构时的接口位置》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

所以,我有一个这样的功能

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”(类型 func(i interface{}) *src.response)作为类型 func(signinresponse) *src.response

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

type TestStruct struct {
    
}

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

}

myFunction2(TestStruct{})

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

我希望它采用 interface{} 作为参数,因为我希望 myfucntion 是通用的,可以采用任何 struct


正确答案


你混淆了两件事。

当您有一个带有签名 func (interface{}) *src.response 的函数时,您确实可以调用它,同时向它传递任何类型的值,但事实并非如此。

发生的情况是,您有另一个函数 processrequest,其参数类型之一是类型为 func (signinresponse) *src.response 的函数。
当您尝试将 func (interface{}) *src.response 类型的值传递给接受 func (signinresponse) *src.response 类型参数的函数时,会发生错误,因为这些参数的类型显然不兼容。

更新。
要了解参数类型不兼容的原因,请考虑 signinresponseinterface{} 在内存中具有不同的存储表示形式;基本上这就是为什么 []t[]interface{} 不兼容的原因,即使你可以这样做 t := t{}; var i 接口{} = t.这个是explained in the FAQ

对于当前的问题,据说最简单的方法是使用匿名函数将值 signinresponse“调整”为 interface{}:传递给 processresponse 类似

func (r SignInResponse) *src.Response {
    return myFunction2(r)
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>