我有一个函数,它接受指向任何切片的指针,并且所述参数的类型为interface{}。我需要确保指针不指向切片nil。package mainimport ( "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: falseslicePointer == nil: false-----dogs2 == nil: trueslicePointer == nil: false 有没有办法在 Golang 中进行这样的检查?
1 回答
HUX布斯
TA贡献1876条经验 获得超6个赞
您可以使用反射判断非 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())
}
}
- 1 回答
- 0 关注
- 113 浏览
添加回答
举报
0/150
提交
取消