【问题标题】:Passing in a type variable into function将类型变量传递给函数
【发布时间】:2017-04-15 05:18:23
【问题描述】:

我试图通过将类型传递给函数来实现类型断言。换句话说,我正在尝试实现这样的目标:

// Note that this is pseudocode, because Type isn't the valid thing to use here
func myfunction(mystring string, mytype Type) {
    ...

    someInterface := translate(mystring)
    object, ok := someInterface.(mytype)

    ...  // Do other stuff
}

func main() {
    // What I want the function to be like
    myfunction("hello world", map[string]string)
}

我需要在myfunction 中使用什么正确的函数声明才能成功执行myfunction 中的类型断言?

【问题讨论】:

    标签: go type-conversion type-assertion


    【解决方案1】:

    @hlin117,

    嘿,如果我正确理解了您的问题并且您需要比较类型,那么您可以这样做:

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

    方法是使用您想要匹配的类型的样本。

    【讨论】:

      猜你喜欢
      • 2014-04-03
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      相关资源
      最近更新 更多