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)sliceFromNewis a pointer to the slice structure- the variable
sliceFromNewitself has value and address - its value is memory address of a slice header
- at that memory address, there’s a
nilslice
- the variable
if sliceFromNew == nil { fmt.Println() }
if *sliceFromNew == nil { fmt.Println() }- the first line wouldn’t print, because
sliceFromNewis notnil, it’s just a pointer variable - the second line prints, because
sliceFromNewpoints to anilslice, dereferencesliceFromNewgives thenilslice
Note
newdoesn’t create the backing array for slice.
makecreates the backing array for slice.