doumao1047 2018-08-05 06:51
浏览 129
已采纳

如何直接使用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-05 22: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部