nil value and its memory

tags: learning go programming

content

Note

for nil stuff, NO memory is allocated, Garbage Collector does not need to manage it.
for empty stuff, memory is allocated, GC needs to track and free the memory.

  • example
mySlice := new([]int)  // returns a pointer to a slice structure
fmt.Printf("mem addr of mySlice: %p", &mySlice)  // 0xsomeaddrB
fmt.Printf("mySlice is: %p", mySlice)  // 0xsomeaddrA
fmt.Printf("value that mySlice points to: %p", *mySlice)  // 0x0
  1. mySlice is a pointer to a slice, its type is *[]int
    • printing mySlice returns 0x1400012e000, which is the address of the slice structure created by new
  2. mySlice itself is a variable, it has its own value and memory
    • printing &mySlice gives the variable’s memory address
  3. %p, &mySlice is different from %p, mySlice
    • the first one is the memory address of this pointer variable, the second one is the value of the pointer variable
  4. *mySlice is a nil slice (mySlice doesn’t point to anything), printing memory address of *mySlice gives 0x0

up

down

reference