An argument as a value

func foo(someSlice  []string){
   //some processiong here
   // just read operations on `someSlice`
}
func main() {
   hugeSlice := []string{"one","two",..., "latestValue"}
   foo(hugeSlice);
}

As we know, in Go arguments in function by default passing as a copy of data, so if the original hugeSlice allocates 10Mb and we pass it in the fuction foo, does it mean that while processing foo a copy of hugeSlice in memory will be created and all the operations inside foo will be processed on that copy data and not from the original slice?

Secondly, does it mean that while processing foo the total memory allocation will be at least ~20Mb, because the copy of hugeSlice was created?

Hi

No the slice is copied but not the underlying array. See this: https://goplay.space/#hK7qi5Czt7Z

%p prints the address of the underlying array

A slice is just a pointer to an array, how long this array is (the capacity) and how much of the array is used (the length). Read about it here https://blog.golang.org/go-slices-usage-and-internals

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.