From 635255152af7da3da6a22698b7a6a6202c9a9ca2 Mon Sep 17 00:00:00 2001 From: Gregory Eremin Date: Tue, 25 Jul 2017 17:50:44 +0400 Subject: [PATCH] Initial commit --- README.md | 8 ++++++++ isnil.go | 15 +++++++++++++++ isnil_test.go | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 README.md create mode 100644 isnil.go create mode 100644 isnil_test.go diff --git a/README.md b/README.md new file mode 100644 index 0000000..d9b2101 --- /dev/null +++ b/README.md @@ -0,0 +1,8 @@ +## Checking for `nil` in Go + +Benchmarks: +``` +BenchmarkIsNilBasic-8 200000000 9.47 ns/op +BenchmarkIsNilInterface-8 200000000 9.18 ns/op +BenchmarkIsNilNil-8 1000000000 2.03 ns/op +``` diff --git a/isnil.go b/isnil.go new file mode 100644 index 0000000..871c11e --- /dev/null +++ b/isnil.go @@ -0,0 +1,15 @@ +package isnil + +import ( + "reflect" +) + +// IsNil returns true if a given value is nil. +func IsNil(i interface{}) bool { + if i == nil { + return true + } + + v := reflect.ValueOf(i) + return v.Kind() == reflect.Ptr && v.IsNil() +} diff --git a/isnil_test.go b/isnil_test.go new file mode 100644 index 0000000..261315e --- /dev/null +++ b/isnil_test.go @@ -0,0 +1,53 @@ +package isnil + +import ( + "testing" +) + +type foo struct{} + +func TestIsNil(t *testing.T) { + cases := []struct { + in interface{} + exp bool + }{ + {1, false}, + {"nope", false}, + {foo{}, false}, + {&foo{}, false}, + {nil, true}, + {(*foo)(nil), true}, + {(interface{})(nil), true}, + } + + for _, tcase := range cases { + if out := IsNil(tcase.in); out != tcase.exp { + if tcase.exp { + t.Errorf("Expected %++v to be nil", tcase.in) + } else { + t.Errorf("Expected %++v to not be nil", tcase.in) + } + } + } +} + +func BenchmarkIsNilBasic(b *testing.B) { + var v *int + for i := 0; i < b.N; i++ { + IsNil(v) + } +} + +func BenchmarkIsNilInterface(b *testing.B) { + var v interface{} + v = (*foo)(nil) + for i := 0; i < b.N; i++ { + IsNil(v) + } +} + +func BenchmarkIsNilNil(b *testing.B) { + for i := 0; i < b.N; i++ { + IsNil(nil) + } +}