-3

I am new to Go, but my understanding is that assignments create copies. The "new" function returns a pointer, which makes sense because then when you assign the return value to a variable, it will only copy the pointer. However, since "make" does not return a pointer, will the newly allocated object not be copied when assigning it to a variable, resulting in a second allocation for the copy?

variable := make([]int, 4, 7)

1 Answers1

0

[]int is a slice, not an array; and slices are basically pointer views into an underlying array:

A slice is a descriptor for a contiguous segment of an underlying array and provides access to a numbered sequence of elements from that array.

Your make line (a) instantiates a [7]int which you never see, and then (b) returns a slice that is essentially just a pointer into the first 4 elements into that array. Since that slice is just a pointer and a length, it is cheap to pass by value. I'm not sure if Go actually creates the slice "internally" to make and then returns it to your variable, or whether it inlines that directly; but the effect either way would be negligible.

From the docs:

That is, executing

make([]T, length, capacity)

produces the same slice as allocating an array and slicing it, so these two expressions are equivalent:

make([]int, 50, 100)
new([100]int)[0:50]
yshavit
  • 42,327
  • 7
  • 87
  • 124
  • Yes, and a map is a little bit more complicated but it's still basically just a pointer to the bucket array (the actual contents) plus some housekeeping data. – hobbs Apr 28 '23 at 20:07