Go 空切片 VS nil切片

在 Go 语言中,空切片和 nil 切片是两种不同的概念。

空切片:

空切片是一个长度和容量都为 0 的切片。你可以通过 make 函数或者切片字面量来创建一个空切片,例如 s := make([]int, 0) 或者 s := []int{}。

  • 空切片不是 nil,即 s != nil。
  • 空切片已经分配了内存空间,所以你可以直接向空切片中添加元素,例如 s = append(s, 1)。

nil 切片:

nil 切片是一个没有初始化的切片,它的值为 nil。

  • nil 切片的长度和容量都为 0,但是与空切片不同,nil 切片没有分配内存空间。
  • 你可以向 nil 切片中添加元素,这时 Go 会为其分配内存空间,例如 var s []int; s = append(s, 1)。
    在大多数情况下,你可以将 nil 切片和空切片等价对待。例如,len(s) 和 cap(s) 对于 nil 切片和空切片都会返回 0,你也可以使用 range 循环来遍历 nil 切片和空切片,都不会产生错误。
    然而,如果你需要区分一个切片是否被初始化,你可以通过 s == nil 来检查一个切片是否为 nil。

测试用例

var s1 []int64
s2 := make([]int64, 0)
s3 := []int64{}

if s1 == nil {
    fmt.Println("s1 是 nil切片")
} else {
    fmt.Println("s1 是 非nil切片")
}
if s2 == nil {
    fmt.Println("s2 是 nil切片")
} else {
    fmt.Println("s2 是 非nil切片")
}
if s3 == nil {
    fmt.Println("s3 是 nil切片")
} else {
    fmt.Println("s3 是 非nil切片")
}

if len(s1) == 0 {
    fmt.Println("s1 无元素")
} else {
    fmt.Println("s1 含有元素")
}
if len(s2) == 0 {
    fmt.Println("s2 无元素")
} else {
    fmt.Println("s2 含有元素")
}
if len(s3) == 0 {
    fmt.Println("s3 无元素")
} else {
    fmt.Println("s3 含有元素")
}

输出

s1 是 nil切片
s2 是 非nil切片
s3 是 非nil切片
s1 无元素
s2 无元素
s3 无元素

推荐
一般我们如果判断一个切片是否包含元素,建议不要根据 if s == nil来判断,推荐使用 len(s) == 0来判断,这样无论是空切片还是nil切片,只要不包含元素,都是返回true。

你可能感兴趣的:(Go,golang,开发语言,后端)