mirror of
https://github.com/mainnika/mongox-go-driver.git
synced 2026-05-23 00:03:36 +00:00
Check for nil interface correctly
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// IsNil function evaluates the interface value to nil
|
||||
func IsNil(i interface{}) bool {
|
||||
|
||||
type iface struct {
|
||||
_ *interface{}
|
||||
ptr unsafe.Pointer
|
||||
}
|
||||
|
||||
unpacked := (*iface)(unsafe.Pointer(&i))
|
||||
if unpacked.ptr == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
return *(*unsafe.Pointer)(unpacked.ptr) == nil
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestIsNil(t *testing.T) {
|
||||
|
||||
testvalues := []struct {
|
||||
i interface{}
|
||||
isnil bool
|
||||
}{
|
||||
{nil, true},
|
||||
{(*string)(nil), true},
|
||||
{([]string)(nil), true},
|
||||
{(map[string]string)(nil), true},
|
||||
{(func() bool)(nil), true},
|
||||
{(chan func() bool)(nil), true},
|
||||
{"", true},
|
||||
{0, true},
|
||||
{append(([]string)(nil), ""), false},
|
||||
{[]string{}, false},
|
||||
{1, false},
|
||||
{"1", false},
|
||||
}
|
||||
|
||||
for _, tt := range testvalues {
|
||||
assert.Equal(t, tt.isnil, IsNil(tt.i))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user