creating slice with new

tags: learning go programming

content

  • for a slice, Go creates:
    • a backing array
    • a slice structure (slice header) that points to the backing array
sliceFromNew := new([]int)
sliceFromMake := make([]int)
  • sliceFromNew is a pointer to the slice structure
    • the variable sliceFromNew itself has value and address
    • its value is memory address of a slice header
    • at that memory address, there’s a nil slice
if sliceFromNew == nil { fmt.Println() }
if *sliceFromNew == nil { fmt.Println() }
  • the first line wouldn’t print, because sliceFromNew is not nil, it’s just a pointer variable
  • the second line prints, because sliceFromNew points to a nil slice, dereference sliceFromNew gives the nil slice

Note

new doesn’t create the backing array for slice.
make creates the backing array for slice.

up

down

reference