reflect.IsNil() Function in Golang with Examples
Last Updated :
10 May, 2020
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() bool
Parameters: 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:
package main
import (
"bytes"
"fmt"
)
func main() {
var body *bytes.Buffer
fmt.Printf( "main(): body == nil ? %t\n" , body == nil)
}
|
Output:
main(): body == nil ? true
Example 2:
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:
return reflect.ValueOf(i).IsNil()
}
return false
}
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...