Passing in a type variable into function

后端 未结 1 1576
梦毁少年i
梦毁少年i 2021-01-17 17:55

I\'m trying to achieve a type assertion by passing in a type into a function. In other words, I\'m trying to achieve something like this:

// Note that this i         


        
相关标签:
1条回答
  • 2021-01-17 18:37

    @hlin117,

    Hey, if I understood your question correctly and you need to compare the types, here's what you can do:

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func myfunction(v interface{}, mytype interface{}) bool {
        return reflect.TypeOf(v) == reflect.TypeOf(mytype)
    }
    
    func main() {
    
        assertNoMatch := myfunction("hello world", map[string]string{})
    
        fmt.Printf("%+v\n", assertNoMatch)
    
        assertMatch := myfunction("hello world", "stringSample")
    
        fmt.Printf("%+v\n", assertMatch)
    
    }
    

    The approach is to use a sample of the type you'd like to match.

    0 讨论(0)
提交回复
热议问题