Course Content
Introduction to GoLang
Introduction to GoLang
Passing Arrays into Functions
A valuable feature is the ability to pass arrays into functions so that we can use these arrays within other scopes, especially when they are locally declared.
The general syntax for an array argument in a function is as follows:
Implementing this in a function would look something like this:
index
func myFunc(arr [5] int) { // code here }
The following example demonstrates passing an array into a function and using it:
index
package main import "fmt" func sumOfAll(arr [10] int) int { total := 0 for i := 0; i < 10; i++ { total += arr[i] } return total } func main() { var numbers = [10] int { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 } fmt.Printf("Sum: %d", sumOfAll(numbers)) }
In Go (Golang), arrays are always passed by value into functions. This means that when we pass an array into a function, a local copy of the original array is created inside the function. Consequently, any modifications made to the array inside the function won't impact the original array because the data being accessed inside the function is a copy of the original array.
The following program illustrates that making changes to the array within the function does not affect the original array:
index
package main import "fmt" func myFunc(nums [3] int) { nums[1] = 10 } func main() { var values = [3] int {1, 2, 3} fmt.Println("Before:", values) myFunc(values) fmt.Println("After: ", values) }
Note
In contrast to passing by value, there's the concept of passing by reference, where a reference to the array or variable is passed into the function. Consequently, modifying the value inside the function also modifies the source. In some programming languages, arrays are passed by reference by default.
Thanks for your feedback!