Handle nil and zero reflection values
Handle nil and zero reflection values
An invalid reflect.Value is not the same as a valid value containing nil, and neither is the same as an ordinary zero such as integer 0. Check validity first. A nil interface produces an invalid Value through ValueOf; a typed nil pointer inside an interface produces a valid pointer Value.
package main
import ( "fmt" "reflect")
func main() { var p *int var x any = p a := reflect.ValueOf(nil) b := reflect.ValueOf(x) fmt.Println(a.IsValid(), a.Kind()) fmt.Println(x == nil, b.IsValid(), b.IsNil())}IsValid is safe for the zero Value. IsNil panics on an invalid Value or an unsupported kind such as int. IsZero checks the zero value of a valid value and panics if it is invalid. Calling Elem on a nil pointer yields an invalid Value; do not continue dereferencing it.
Expected output:
false invalidfalse true trueMissing map entries versus zero values
package main
import ( "fmt" "reflect")
func main() { v := reflect.ValueOf(map[string]int{"stock": 0}) a := v.MapIndex(reflect.ValueOf("stock")) b := v.MapIndex(reflect.ValueOf("missing")) fmt.Println(a.IsValid(), a.IsZero(), b.IsValid())}An existing map key holding zero remains valid. A missing key produces an invalid Value. With an ordinary typed map, use the comma-ok lookup instead. Reflection helpers should document which nil-like cases they accept rather than treating every zero as absent.
Expected output:
true true falseTry it locally
Compare a nil slice and an allocated empty slice using IsNil and Len. Print both pairs.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reflection and unsafe 04: Handle nil and zero reflection values
Check the lesson objective before moving on.
Which check comes first for an arbitrary reflect.Value?
What does a missing map key return through MapIndex?