...

/

Slices with Functions

Slices with Functions

This lesson explains handling slices as parameters to the functions in detail.

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:

Press + to interact
package main
import "fmt"
func sum(a []int) int { // function that sums integers
s := 0
for i := 0; i < len(a); i++ {
s += a[i]
}
return s
}
func main() {
var arr = [5]int{0,1,2,3,4} // declare an array
fmt.Println(sum(arr[:])) // passing slice to the function
}

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 ...