Passing array to function in Golang
An array can be passed to the function in Go language like any other normal variable. There are two way to pass array to the function, either you can pass array with fixed size or generic without specifying size, generic mean empty array size.
1. Fixed size array2. Array without specifying size

Fixed size array

A function parameter specified with fixed size array, it can only accept parameter with fixed size. If array size is not equal to the specified size, it will throw compile time error.
Function parameter with fixed size array
 1 package main
 2 
 3 import "fmt"
 4 
 5 func main() {
 6 
 7 	var array = [10]int{0, 10, 20, 30, 40, 50, 60, 70, 80, 90}
 8 	var array1 = [10]int{11, 22, 33, 44, 55}
 9 
 10 	fmt.Printf("A sum of first array  elements : %d", elementSum(array))
 11 	fmt.Printf("\nA sum of second array elements : %d", elementSum(array1))
 12 }
 13 
 14 func elementSum(arr [10]int) int {
 15 	sum := 0
 16 	for _, element := range arr {
 17 		sum = sum + element
 18 	}
 19 	return sum
 20 }
In the above example, we have define two array with element 10 but array elements can have less than the specified size. A function define with name elementSum which accept array having 10 element. If array size is not equal to 10, it will throw error.
Output
 1 A sum of first array  elements : 450
 2 A sum of second array elements : 165

Array without specifying size

A dynamic size array specified without providing size (empty square bracket). If size not specify then array need to be iterate using range keyword. A function define with empty array as parameter can be used to find sum of elements having different size of array.
Function parameter as array without specifying size
 1 package main
 2 
 3 import "fmt"
 4 
 5 func main() {
 6 
 7 	// array define without specifying size
 8 	var array = []int{0, 10, 20, 30, 40, 50, 60, 70, 80, 90}
 9 	var array1 = []int{11, 22, 33, 44, 55}
 10 
 11 	fmt.Printf("A sum of first array  elements : %d", elementSum(array))
 12 	fmt.Printf("\nA sum of second array elements : %d", elementSum(array1))
 13 }
 14 
 15 // a function accept array without fixed size
 16 func elementSum(arr []int) int {
 17 	sum := 0
 18 	for _, element := range arr {
 19 		sum = sum + element
 20 	}
 21 	return sum
 22 }
In the above example, we have define two array without specifying size of array. A both array initialized with different number of elements. A function parameter with array is not fixed, Hence it will allows to find sum of array with empty array.
Output
 1 A sum of first array  elements : 450
 2 A sum of second array elements : 165
Note : It is also possible to use pointer to pass array to the function. A function receive an address of array and traverse element by using pointer arithmetic operation.
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us