VOOZH about

URL: https://www.geeksforgeeks.org/go-language/how-to-pass-an-array-to-a-function-in-golang/

⇱ How to pass an Array to a Function in Golang? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to pass an Array to a Function in Golang?

Last Updated : 12 Jul, 2025

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:


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:

  1. Array Declaration:
    • Use the syntax var arrayName [size]type to declare an array.
    var numbers [5]int // An array of 5 integers
  2. 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.
  3. 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:


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.

Comment

Explore