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

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

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")
	}
}

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:

确定