dongqiang1894 2018-12-20 02:54
浏览 480
已采纳

使用反射确定类型是否为字符串

Some of the existing answers on here about how to determine the type of an object at runtime..god help us

if reflect.TypeOf(err) ==  string {

}

that doesn't compile

if reflect.TypeOf(err) ==  "string" {

}

neither does that or this:

if reflect.TypeOf(err).Kind() ==  "string" {

}

how do we do this?

If I use the typeof function given by one of the answers, I get:

enter image description here

  • 写回答

2条回答 默认 最新

  • donglun4682 2018-12-20 03:01
    关注

    Compare like string

    if reflect.TypeOf(err).String() == "string" {
        fmt.Println("hello")
    }
    

    Or using type assertions

    type F = func()
    
    func typeof(v interface{}) string {
        switch v.(type) {
        case int:
            return "int"
        case string:
            return "string"
        case F:
            return "F"
        //... etc
        default:
            return "unknown"
        }
    }
    

    Then

    var f F
    if typeof(f) == "F"{
        fmt.Println("hello F")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?