完整代碼在這里: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 } }基本上,我想做一些類似的事情f.Type()=="string"或者f.Type()=="uint64"或者f.Type()=="int64"直接代替
3 回答

米琪卡哇伊
TA貢獻1998條經驗 獲得超6個贊
聲明感興趣類型的變量。通常最好在程序包級別執行此操作。
var (
stringType = reflect.TypeOf("")
uint64Type = reflect.TypeOf(uint64(0))
... and so on
)
與這些類型進行比較:
if f.Type() == stringType {
...
}
無法使用,f.Type()== "string"因為無法分配字符串來反映類型值,反之亦然。
另一個選擇是調用Type.String(),但是比較類型通常比字符串更好:
if f.Type().String == "string" {
...
}
- 3 回答
- 0 關注
- 368 瀏覽
添加回答
舉報
0/150
提交
取消