How does nil slice and map work?

tags: learning go practice

content

var nilMap map[string]int     // 0 bytes for map structure
emptyMap := map[string]int{}  // ~48+ bytes for initial hash table structure
  • for maps, Go creates some data structure for it
  • for nil map, NO memory is allocated, no data structure is allocated
  • for empty map, the data structure is created
mySlice := new([]int)
// `mySlice` is of type *[]int (pointer to slice)
// `mySlice` points to a slice that is nil
  • for slices, Go also creates some sort of similar data structure
    • Go creates an underlying array with no elements for empty slice
    • nil slice means there’s no underlying array
    • only the slice header is created, it doesn’t point to anything

up

down

reference