我有一个函数,它接受指向任何切片的指针,并且所述参数的类型为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 中进行这样的检查?
暮色呼如
相关分类