1 回答
TA貢獻1963條經驗 獲得超6個贊
Value.IsZero()報告包裝的值是否是其類型的零值。這與reflect.Value自身為零(reflect.Value其零值是結構)不同。
另請注意,t在您的代碼中不是結構值,它是指向結構的指針。用于Value.Elem()導航到包裝的結構值(或不從指針開始)。
如果該字段不存在,Value.FieldByName()則返回 的零值reflect.Value,而不是reflect.Value持有某種類型的零值的非零值;如果找不到字段,則沒有類型信息。
因此,要檢查該字段是否不存在,請reflect.Value通過將其與以下內容進行比較來檢查其本身是否為零reflect.Value{}:
if field == (reflect.Value{}) {
log.Printf("Field %s was not on the struct", name)
}
測試它:
type test struct {
A bool
B bool
x bool
}
v := new(test)
metaValue := reflect.ValueOf(v).Elem()
for _, name := range []string{"A", "x", "y"} {
field := metaValue.FieldByName(name)
if field == (reflect.Value{}) {
log.Printf("Field %s was not on the struct", name)
}
}
這將輸出(在Go Playground上嘗試):
2009/11/10 23:00:00 Field y was not on the struct
- 1 回答
- 0 關注
- 126 瀏覽
添加回答
舉報
