nil is a valid slice

nil is a valid slice of length 0. This means that,

  • You should not return a slice of length zero explicitly. Return nil instead.

    BadGood
    ```go if x == "" { return []int{} } ``` ```go if x == "" { return nil } ```
  • To check if a slice is empty, always use len(s) == 0. Do not check for nil.

    BadGood
    ```go func isEmpty(s []string) bool { return s == nil } ``` ```go func isEmpty(s []string) bool { return len(s) == 0 } ```
  • The zero value (a slice declared with var) is usable immediately without make().

    BadGood
    ```go nums := []int{} // or, nums := make([]int) if add1 { nums = append(nums, 1) } if add2 { nums = append(nums, 2) } ``` ```go var nums []int if add1 { nums = append(nums, 1) } if add2 { nums = append(nums, 2) } ```

Remember that, while it is a valid slice, a nil slice is not equivalent to an allocated slice of length 0 - one is nil and the other is not - and the two may be treated differently in different situations (such as serialization).

© Kimi Tsai all right reserved.            Updated : 2023-07-12 09:05:01

results matching ""

    No results matching ""

    results matching ""

      No results matching ""