-2
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

blackgreen
  • 34,072
  • 23
  • 111
  • 129
keepeye
  • 19
  • 2

1 Answers1

2

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