Slices with Functions
Explore how to work with slices in Go by learning to pass slices to functions for efficient array operations. Understand creating slices with the make function and contrast it with new to manage memory correctly. This lesson provides practical insights to handle slices in your Go programs confidently.
We'll cover the following...
Passing a slice to a function #
If you have a function that must operate on an array, you probably always want to declare the formal parameter to be a slice. When you call the function, slice the array to create (efficiently) a slice reference and pass that. For example, here is a program that sums all elements in an array:
In the above program, we have a function sum, that takes slice of an array a as a parameter and returns the sum of the elements present in a. Look at its header at line 4. In the main function, at line 13, we declare an array arr of length 5 and pass it to the sum function on the next line. We write arr[:], which is enough to pass the array arr as the reference.
Creating a slice with make()
Often the ...