【发布时间】:2019-01-14 06:12:27
【问题描述】:
我创建了几种类型,包括接口:
// 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".User) middleware.Responder) 来输入 profile.GetProfileHandlerFuncgo
【问题讨论】:
-
“现在我认为我可以做到以上逻辑” 不,你可以不。
func(params profile.GetProfileParams, principal *models.User) middleware.Responder与func(GetProfileParams, interface{}) middleware.Responder不同。即:*models.User与interface{}的类型不同。 -
GetProfileHandlerFunc类型实现的接口无关紧要,错误并没有说明接口,它告诉您不能将 A 转换为 B,其中 A 是 func 文字 @987654331 @ 和 B 是函数类型GetProfileHandlerFunc。 -
... 和
int("hello world")一样,是在两种不兼容的类型之间进行转换。 -
@Himanshu。不,你不可能看到这一点,因为在 Go 中这是不可能的。另见golang.org/doc/faq#convert_slice_of_interface。 Go 的类型系统不像你想象的那样工作。
interface{}并不意味着“随便”,它意味着interface{},而只是interface{}。您可以将任何内容分配给interface{},但作为一种类型,它是interface{}和nothing else。 -
您可能误解了您所看到的内容,或者代码也已损坏,无法像您的那样编译。