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

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

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

图片转代码服务由CSDN问答提供 功能建议

关于如何在运行时确定对象类型的一些现有答案。.god帮助我们< / p>

 如果reflect.TypeOf(err)==字符串{
 
} 
   
 
 

编译

 如果reflect.TypeOf(err)==“字符串” {
 
} 
   
 
 

也不是这样:

 如果reflect.TypeOf(err).Kind()==“ string” {
 
} 
   
 
 

我们该怎么做?

如果我使用答案之一给出的typeof函数,我会得到:

”在此处输入图片描述“

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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")
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douli1854 2018-12-20 12:59

    To compare types using reflect, compare reflect.Type values:

    var stringType = reflect.TypeOf("") // this can be declared at package-level
    
    if reflect.TypeOf(v) == stringType {
        // v has type string
    }
    

    Given an arbitrary type name X, you can construct the type using:

    var xType = reflect.TypeOf((*X)(nil)).Elem()
    
    if reflect.TypeOf(v) == xType {
        // v has type X
    }
    

    If you want to check to see if a value is some type, then use a type assertion:

    if _, ok := v.(string); ok {
       // v is a string
    }
    

    If you want to map types to strings, use a map keyed by reflect.Type:

    var typeName = map[reflect.Type]string{
        reflect.TypeOf((*int)(nil)).Elem():    "int",
        reflect.TypeOf((*string)(nil)).Elem(): "string",
        reflect.TypeOf((*F)(nil)).Elem():      "F",
    }
    
    ...
    
    if n, ok := typeName[reflect.TypeOf(f)]; ok {
        fmt.Println(n)
    } else {
        fmt.Println("other")
    }
    
    评论
    解决 无用
    打赏 举报