接口断言失败,类型为gin.HandlerFunc。

huangapple go评论123阅读模式
英文:

Assertion failed for interface as gin.HandlerFunc

问题

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. )
  6. func Foo(ctx *gin.Context) {}
  7. func main() {
  8. var v interface{}
  9. v = Foo
  10. _, ok := v.(func(*gin.Context))
  11. fmt.Println(ok) // true
  12. _, ok = v.(gin.HandlerFunc)
  13. fmt.Println(ok) // false
  14. }

我有一个接口类型的函数,并希望将其转换为gin.HandlerFunc,但我不明白为什么第二个断言失败了,希望能得到答案,谢谢。

英文:
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. )
  6. func Foo(ctx *gin.Context) {}
  7. func main() {
  8. var v interface{}
  9. v = Foo
  10. _, ok := v.(func(*gin.Context))
  11. fmt.Println(ok) // true
  12. _, ok = v.(gin.HandlerFunc)
  13. fmt.Println(ok) // false
  14. }

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

  1. func handlerFunc(v interface{}) gin.HandlerFunc {
  2. switch v := v.(type) {
  3. case func(*gin.Context):
  4. return v
  5. case gin.HandlerFunc:
  6. return v
  7. default:
  8. panic("unexpected type")
  9. }
  10. }
英文:

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{}:

  1. func handlerFunc(v interface{}) gin.HandlerFunc {
  2. switch v := v.(type) {
  3. case func(*gin.Context):
  4. return v
  5. case gin.HandlerFunc:
  6. return v
  7. default:
  8. panic("unexpected type")
  9. }
  10. }

huangapple
  • 本文由 发表于 2022年5月17日 10:36:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/72267580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定