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

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

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

报告相同问题?

悬赏问题

  • ¥15 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示