I have a struct as below:
type Demo struct{
A string
B string
}
and I have a instance of it as below:
demo := Demo{A:"a"}
the field of A has been assigned value explicit but field B not. Now, I want to know are there exist some method that I can get the field of Instance A which has been assigned value through reflection?
Here I want to get field A.
It's not possible to determine if a field was explicitly assigned a value, but it is possible to determine if there's a field that's not equal to the field's zero value.
Loop through the fields. Return true if a field's value is not equal to the zero value for the field's type.
func hasNonZeroField(s interface{}) bool {
v := reflect.ValueOf(s)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
t := v.Type()
for i := 0; i < t.NumField(); i++ {
sf := t.Field(i)
fv := v.Field(i)
switch sf.Type.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
if !fv.IsNil() {
return true
}
case reflect.Struct:
if hasNonZeroField(fv.Interface()) {
return true
}
// case reflect.Array:
// TODO: call recursively for array elements
default:
if reflect.Zero(sf.Type).Interface() != fv.Interface() {
return true
}
}
}
return false
}