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
- if x == "" {
- return []int{}
- }
- if x == "" {
- return nil
- }
- To check if a slice is empty, always use
len(s) == 0
. Do not check fornil
.
BadGood
- func isEmpty(s []string) bool {
- return s == nil
- }
- func isEmpty(s []string) bool {
- return len(s) == 0
- }
- The zero value (a slice declared with
var
) is usable immediately withoutmake()
.
BadGood
- nums := []int{}
- // or, nums := make([]int)
- if add1 {
- nums = append(nums, 1)
- }
- if add2 {
- nums = append(nums, 2)
- }
- var nums []int
- if add1 {
- nums = append(nums, 1)
- }
- if add2 {
- nums = append(nums, 2)
- }