Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.IsNil() Function in Golang is used to check whether its argument v is nil. The argument must be a chan, func, interface, map, pointer, or slice value; if it is not, IsNil panics.
Note: IsNil is not always equivalent to a regular comparison with nil in Go. For example, if v was created by calling ValueOf with an uninitialized interface variable i, i==nil will be true but v.IsNil will panic as v will be the zero Value.
Syntax:
func (v Value) IsNil() boolParameters: This function does not accept any parameter.
Return Value: This function returns whether its argument v is nil or not.
Below examples illustrate the use of above method in Golang:
Example 1:
// Golang program to illustrate // reflect.IsNil() Function package main import ( "bytes" "fmt" ) // Main function func main() { var body *bytes.Buffer fmt.Printf( "main(): body == nil ? %t\n" , body == nil) } |
Output:
main(): body == nil ? true
Example 2:
// Golang program to illustrate // reflect.IsNil() Function package main import ( "fmt" "reflect" ) func isNilFixed(i interface{}) bool { if i == nil { return true } switch reflect.TypeOf(i).Kind() { case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice: //use of IsNil method return reflect.ValueOf(i).IsNil() } return false } // Main function func main() { t := reflect.TypeOf(5) arr := reflect.ArrayOf(4, t) inst := reflect.New(arr).Interface().(*[4] int ) for i := 1; i <= 4; i++ { inst[i-1] = i*i } fmt.Println(isNilFixed(inst)) } |
Output:
false