What’s the difference between nil and empty

tags: learning go programming diff-between

content

example code:

var a []int  // a is nil, a == nil gives true
b := new([]int)  // *b is nil, *b == nil gives true
c := make([]int)  // c is NOT nil, c == nil gives false
len(b)  // 0
len(c)  // 0
  • nil means no value, uninitialized
    • for slice, it means no underlying array
    • for map, it means no map allocated
    • for pointer, it means the pointer points to nothing*
  • empty means it has a value, but contains no element
    • the variable is initialized, but has nothing

up

down

reference