doumao1047 2018-08-05 14:51
浏览 128
已采纳

如何直接使用golang反射f.Type()==“ string”?

Full code is here: https://pastebin.com/xC1uQVBC

   type UDD struct {
                        A string //content = "John"
                        B string //content = "Male"
                        C string //content = "12345678"
                        D int64 //content = ""
                        E uint64 //content = ""
                        Z string //content = "FIrst time user"
   }


    reflect_UDD := reflect.ValueOf(&UDD).Elem()
    typeOf_UDD := reflect_UDD.Type()




    for i := 0; i < reflect_UDD.NumField(); i++ {
           f := reflect_UDD.Field(i)

           if(f.Type()==reflect.TypeOf("string")){ 
                //i would like to f.Type()=="string" directly... 
                //how is this possible and also for uint64 and int64 etc
           }
     }

Basically, I would like to do something along the lines of

f.Type()=="string"

or

f.Type()=="uint64"

or

f.Type()=="int64"

directly instead

  • 写回答

3条回答 默认 最新

  • duanluanhui8348 2018-08-06 06:51
    关注

    Change f.Type() to f.Kind(), then use reflect Type to do judgement, supported types could be found https://godoc.org/reflect#Kind. please see full example https://play.golang.org/p/Zydi7t3UBNJ

          switch f.Kind() {
        case reflect.Int64:
            fmt.Println("got int64")
        case reflect.String:
            fmt.Println("got string")
        case reflect.Uint64:
            fmt.Println("got Unit64")
        default:
            fmt.Println("found nothing")        
       }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#c语言#的问题:这个六个方程输入程序可以得出角度角速度角加速度
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油