1
0
Fork 0

Initial commit

This commit is contained in:
Gregory Eremin 2017-07-25 17:50:44 +04:00
commit 635255152a
3 changed files with 76 additions and 0 deletions

8
README.md Normal file
View File

@ -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
```

15
isnil.go Normal file
View File

@ -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()
}

53
isnil_test.go Normal file
View File

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