- nil是一个有效的slice
- Bad
- Good
- Bad
- Good
- Bad
- Good
nil是一个有效的slice
nil 是一个有效的长度为 0 的 slice,这意味着:
- 不应明确返回长度为零的切片,而应该直接返回 nil 。
Bad
if x == "" {return []int{}}
Good
if x == "" {return nil}
- 若要检查切片是否为空,始终使用
len(s) == 0,不要与 nil 比较来检查。
Bad
func isEmpty(s []string) bool {return s == nil}
Good
func isEmpty(s []string) bool {return len(s) == 0}
- 零值切片(通过 var 声明的切片)可直接使用,无需调用 make 创建。
Bad
nums := []int{}// or, nums := make([]int)if add1 {nums = append(nums, 1)}if add2 {nums = append(nums, 2)}
Good
var nums []intif add1 {nums = append(nums, 1)}if add2 {nums = append(nums, 2)}
