reflect.IsNil() Function in Golang with Examples

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


Output:

main(): body == nil ? true

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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))
}

chevron_right


Output:

false

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Small things always make you to think big

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.