Created
February 1, 2019 20:21
-
-
Save miguelmota/faca748b3c8598f2abf322b51b542d24 to your computer and use it in GitHub Desktop.
Golang check if interface value is nil
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The above func does not work for slices, etc. A better version that includes all needed kinds of 'Kinds':