检查指针是否指向零切片



我有一个函数,它接受指向任何切片的指针,所述参数的类型为interface{}.

我需要确保指针不指向nil切片。

package main
import (
"fmt"
)
type Dog struct {
Name string
Age  int
}
func main() {
var slicePointer interface{}
// We only want slices that were initialized with `make()`.
dogs1 := make([]Dog, 0)
fmt.Println("dogs1 == nil:", dogs1 == nil)
slicePointer = &dogs1
fmt.Println("slicePointer == nil:", slicePointer == nil)
fmt.Println("-----")
// This needs to be caught, as the slice is `nil`.
var dogs2 []Dog
fmt.Println("dogs2 == nil:", dogs2 == nil)
slicePointer = &dogs2
fmt.Println("slicePointer == nil:", slicePointer == nil)
}

输出:

dogs1 == nil: false
slicePointer == nil: false
-----
dogs2 == nil: true
slicePointer == nil: false   

有没有办法在 Golang 中进行这样的检查?

您可以使用反射来判断非 nil 接口是否具有 nil 指针值:

fmt.Println(reflect.ValueOf(slicePointer).Elem().IsNil())

对于最安全的方法:

if slicePointer!=nil {
v:=reflect.ValueOf(slicePointer)
if v.Kind()==reflect.Ptr {
fmt.Println(v.Elem().IsNil())
}
}

相关内容

  • 没有找到相关文章

最新更新