英文:
Assertion failed for interface as gin.HandlerFunc
问题
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func Foo(ctx *gin.Context) {}
func main() {
var v interface{}
v = Foo
_, ok := v.(func(*gin.Context))
fmt.Println(ok) // true
_, ok = v.(gin.HandlerFunc)
fmt.Println(ok) // false
}
我有一个接口类型的函数,并希望将其转换为gin.HandlerFunc
,但我不明白为什么第二个断言失败了,希望能得到答案,谢谢。
英文:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func Foo(ctx *gin.Context) {}
func main() {
var v interface{}
v = Foo
_, ok := v.(func(*gin.Context))
fmt.Println(ok) // true
_, ok = v.(gin.HandlerFunc)
fmt.Println(ok) // false
}
I have a function of interface type and want to convert it to gin.HandlerFunc, but what I can't understand is why the second assertion fails, I hope to get an answer, thank you
答案1
得分: 2
尽管gin.HandlerFunc
可以赋值给func(*gin.Context)
,反之亦然,但它们是不同的类型。func(*gin.Context)
不是gin.HandlerFunc
。
使用以下代码从interface{}
获取gin.HandlerFunc
:
func handlerFunc(v interface{}) gin.HandlerFunc {
switch v := v.(type) {
case func(*gin.Context):
return v
case gin.HandlerFunc:
return v
default:
panic("unexpected type")
}
}
英文:
Although a gin.HandlerFunc
is assignable to a func(*gin.Context)
and vice versa, they are different types. A func(*gin.Context)
is not a gin.HandlerFunc
.
Use this code to get a gin.HandlerFunc
from an interface{}
:
func handlerFunc(v interface{}) gin.HandlerFunc {
switch v := v.(type) {
case func(*gin.Context):
return v
case gin.HandlerFunc:
return v
default:
panic("unexpected type")
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论