How to pass an Array to a Function in Golang?
Last Updated :
25 Oct, 2024
Improve
In Go, arrays are used to store a fixed-length collection of data of the same type. To manage this data effectively, you may often need to pass arrays to functions. In this article we will learn "How to pass an Array to a Function in Golang".
Example:
package main
import "fmt"
// Function to calculate the average of an array
func calculateAverage(arr [6]int, size int) int {
var sum int
for _, value := range arr {
sum += value
}
return sum / size
}
func main() {
scores := [6]int{67, 59, 29, 35, 4, 34}
average := calculateAverage(scores, len(scores))
fmt.Printf("%d\n", average)
}
Output
38
Explanation:
In this example, the calculateAverage()
function takes an array of integers and its size as arguments. It computes the average of the array elements and returns it. The main
function initializes an array called scores
and calls the average calculation function.
Key Points:
- Array Declaration:
- Use the syntax
var arrayName [size]type
to declare an array.
var numbers [5]int // An array of 5 integers
- Use the syntax
- Passing Arrays:
- In Go, arrays are passed to functions by value, meaning the function receives a copy of the array. Changes made inside the function do not affect the original array.
- Pointer to Modify Original Array:
- If you want to modify the original array, you should pass a pointer to it.
func modifyArray(arr *[5]int) {
for i := range arr {
arr[i] += 10 // Increment each element by 10
}
}
Modifying an Array
Example:
package main
import "fmt"
// Function to increment each element of the array
func incrementArray(arr *[5]int) {
for i := range arr {
arr[i]++ // Increment each element by 1
}
}
func main() {
values := [5]int{1, 2, 3, 4, 5}
// Modifying the array
incrementArray(&values)
fmt.Println("Incremented array:", values)
}
Output
Incremented array: [2 3 4 5 6]
Passing arrays to functions in Go allows for efficient data management. Understanding how to pass and modify arrays will help you write effective Go programs.