Go Pointers & new vs make
November 15, 2020
xPtr *int – xPtr is a pointer to an int
*xPtr – “*” is the dereference operator, yields the value pointed to by xPtr
Given: x:=5 , then &x – returns a *int a “pointer to an int”
new() – Takes a type as an arguement and allocates enough memory to hold a value of that type and returns a pointer
Its easy to get confused on the difference between new() and make() in Golang
new()
- allocates memory and “zeros” it.
- That is
new(T)allocates zeroed storage for a new item of type T and returns its address a value of type *T - Said more succintly “It returns a pointer to a newly allocated zero value of type T”
make(T, args)
- can create slices, maps and channels only
- returns “initialized” but not “zeroed” value of type T (not *T)
- to obtain a pointer allocate with new or take the address of a variable explicitly