在Golang中实现接口类型到函数类型
我创建了几种类型,包括接口:在Golang中实现接口类型到函数类型,go,interface,Go,Interface,我创建了几种类型,包括接口: // GetProfileHandlerFunc turns a function with the right signature into a get profile handler type GetProfileHandlerFunc func(GetProfileParams, interface{}) middleware.Responder // Handle executing the request and returning a response
// GetProfileHandlerFunc turns a function with the right signature into a get profile handler
type GetProfileHandlerFunc func(GetProfileParams, interface{}) middleware.Responder
// Handle executing the request and returning a response
func (fn GetProfileHandlerFunc) Handle(params GetProfileParams, principal interface{}) middleware.Responder {
return fn(params, principal)
}
// GetProfileHandler interface for that can handle valid get profile params
type GetProfileHandler interface {
Handle(GetProfileParams, interface{}) middleware.Responder
}
现在在我的api实现包中。我正在使用逻辑来处理请求参数。我正试图将GetProfileHandlerFunc
分配给另一个类型,因为它实现了GetProfileHandler
接口,正如您在上面看到的那样
api.ProfileGetProfileHandler = profile.GetProfileHandlerFunc(func(params profile.GetProfileParams, principal *models.User) middleware.Responder {
// contains logic to handle the request
}
现在我想我能做到以上逻辑。但是我得到了类型不匹配错误
无法转换func文字(类型func(profile.GetProfileParams,
*“userproj/models”。用户)
中间件.Responder)以键入profile.GetProfileHandlerFuncgo
重点是:
如果你有这样一个函数
func A(param interface{}) {}
在调用函数a时,可以将任何内容传递给param
A(10)
A(true)
A(nil)
因为接口{}意味着一切。因此,您的handle func定义:
type GetProfileHandlerFunc func(GetProfileParams, interface{}) middleware.Responder
表示接受两个参数的函数GetProfileHandlerFunc,第一个参数类型为GetProfileParams,第二个参数类型为interface{}。这意味着第二个参数可以是任何东西
但是
表示采用两个参数的函数,第一个为GetProfileParams类型,第二个为*models.User类型。那么,你认为他们是一样的吗?没有
我需要一个函数可以将任何东西作为第二个参数,而不是一个只能将用户作为第二个函数的函数
当你叫你把手的时候
GetProfileHandlerFunc(params, 10) // this is ok
这对我来说可以吗
func(params profile.GetProfileParams, principal *models.User) middleware.Responder
没有
正确的方法是:
api.ProfileGetProfileHandler = profile.GetProfileHandlerFunc(func(params profile.GetProfileParams, principal interface) middleware.Responder {
user:=principal.(*model.User) // watch this.
}
“现在我想我能做到以上逻辑”不,你不能
func(params profile.GetProfileParams,principal*models.User)中间件。响应程序
与func(GetProfileParams,interface{})中间件不同。响应程序
。也就是说:*模型。用户
与接口{}
的类型不同。无论GetProfileHandlerFunc
类型实现什么接口,错误并没有说明任何关于接口的内容,它告诉您不能将A转换为B,其中A是func文本func(params profile.GetProfileParams,principal*models.User)中间件.Responder
和B是func类型GetProfileHandlerFunc
…这与尝试执行int(“hello world”)相同
,您正在两个不兼容的类型之间进行转换。@Himanshu。不,您不可能看到这一点,因为这在Go中是不可能的。另请参见。Go的类型系统没有按照您的想法工作。interface{}
并不表示“无论”它的意思是interface{}
而且只表示interface{}
。您可以将任何内容分配给接口{}
,但作为一种类型,它是接口{}
而不是其他任何内容。您可能误解了所看到的内容,或者代码也被破坏了,无法像您的一样编译。
api.ProfileGetProfileHandler = profile.GetProfileHandlerFunc(func(params profile.GetProfileParams, principal interface) middleware.Responder {
user:=principal.(*model.User) // watch this.
}