简体   繁体   中英

How do I f.Type()==“string” directly using golang reflect?

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

Declare variables for the types of interest. It's usually best to do this at package level.

var ( 
  stringType = reflect.TypeOf("")
  uint64Type = reflect.TypeOf(uint64(0))
  ... and so on
)

Compare to these types:

if f.Type() == stringType { 
    ...
}

It's not possible to use f.Type()== "string" because strings are not assignable to reflect.Type values or vice versa.

Another option is to call Type.String() , but it's usually better to compare types than strings:

if f.Type().String == "string" { 
    ...
}

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")        
   }
f.Type().Kind().String()=="Uint64"

请参阅反射

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM