What does new do in Go
tags: learning go programming
content
Note
new(Type)is the same as&Type{}
-
newcommand 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 rangeerror- the length of
mySliceis0 - because
newallocates memories for[]int, which has length0!
- the length of
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]