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 nilinstead.

BadGood

  1. if x == "" {
  2. return []int{}
  3. }
  1. if x == "" {
  2. return nil
  3. }
  • To check if a slice is empty, always use len(s) == 0. Do not check fornil.

BadGood

  1. func isEmpty(s []string) bool {
  2. return s == nil
  3. }
  1. func isEmpty(s []string) bool {
  2. return len(s) == 0
  3. }
  • The zero value (a slice declared with var) is usable immediately withoutmake().

BadGood

  1. nums := []int{}
  2. // or, nums := make([]int)
  3.  
  4. if add1 {
  5. nums = append(nums, 1)
  6. }
  7.  
  8. if add2 {
  9. nums = append(nums, 2)
  10. }
  1. var nums []int
  2.  
  3. if add1 {
  4. nums = append(nums, 1)
  5. }
  6.  
  7. if add2 {
  8. nums = append(nums, 2)
  9. }