What does new do in Go

tags: learning go programming

content

Note

new(Type) is the same as &Type{}

  • new command allocates memory, returns the memory address (meaning pointer)

    • it only allocates memory, that’s all it does
    • there’s more to variable declaration and initialization than memory allocation
  • the below code doesn’t work, throwing index out of range error

    • the length of mySlice is 0
    • because new allocates memories for []int, which has length 0!
mySlice := new([]int)
(*mySlice)[1] = 1  // panic: runtime error: index out of range [1] with length 0
  • the below code does NOT throw error
mySlice := new([3]int)
(*mySlice)[1] = 1  // print out *mySlice is [1 0 0]

up

down

reference