Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created February 1, 2019 20:21
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miguelmota/faca748b3c8598f2abf322b51b542d24 to your computer and use it in GitHub Desktop.
Save miguelmota/faca748b3c8598f2abf322b51b542d24 to your computer and use it in GitHub Desktop.
Golang check if interface value is nil
package main
import (
"fmt"
"reflect"
)
func main() {
var v *string
fmt.Println(isNil(v)) // true
}
func isNil(v interface{}) bool {
return v == nil || (reflect.ValueOf(v).Kind() == reflect.Ptr && reflect.ValueOf(v).IsNil())
}
@tomasji
Copy link

tomasji commented Jan 29, 2023

The above func does not work for slices, etc. A better version that includes all needed kinds of 'Kinds':

func IsNil(v interface{}) bool {
	if v == nil {
		return true
	}
	val := reflect.ValueOf(v)
	switch val.Kind() {
	case reflect.Chan, reflect.Func, reflect.Map, reflect.Pointer, reflect.UnsafePointer, reflect.Interface, reflect.Slice:
		return val.IsNil()
	}
	return false
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment