Open In App

How to pass an Array to a Function in Golang?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Arrays in Golang or Go programming language is much similar to other programming languages. In the program, sometimes we need to store a collection of data of the same type, like a list of student marks. Such type of collection is stored in a program using an Array. An array is a fixed-length sequence that is used to store homogeneous elements in the memory. In Go language, you are allowed to pass an array as an argument in the function. For passing an array as an argument in the function you have to first create a formal parameter using the following below as follows: 

Syntax:  

// For sized array
func function_name(variable_name [size]type){
// Code
}

Using this syntax you can pass 1 or multiple-dimensional arrays to the function. Let us discuss this concept with the help of an example:

Example: 

Go




// Go program to illustrate how to pass an
// array as an argument in the function
package main
 
import "fmt"
 
// This function accept
// an array as an argument
func myfun(a [6]int, size int) int {
    var k, val, r int
 
    for k = 0; k < size; k++ {
        val += a[k]
    }
 
    r = val / size
    return r
}
 
// Main function
func main() {
 
    // Creating and initializing an array
    var arr = [6]int{67, 59, 29, 35, 4, 34}
    var res int
 
    // Passing an array as an argument
    res = myfun(arr, 6)
    fmt.Printf("Final result is: %d ", res)
}


Output: 

Final result is: 38 

Explanation: In the above example, we have a function named as myfun() which accepts an array as an argument. In the main function, we passed arr[6] of int type to the function with the size of the array and the function return the average of the array.

In Go, arrays are passed to functions as values, not as references. This means that changes made to the array inside the function will not affect the original array. To pass an array to a function in Go, you simply need to pass the array as an argument to the function.

Here’s an example that demonstrates how to pass an array to a function in Go:
 

Go




package main
 
import "fmt"
 
func printArray(array []int) {
    for _, value := range array {
        fmt.Println(value)
    }
}
 
func main() {
    array := []int{1, 2, 3, 4, 5}
    printArray(array)
}


Output:

1
2
3
4
5

As we can see, the array is passed to the function printArray as an argument, and the function can access the elements of the array just as it would with any other value.

It’s also possible to modify the elements of the array inside the function, but as I mentioned earlier, these changes will not affect the original array. To make changes to the original array, you would need to pass a pointer to the array to the function.



Last Updated : 02 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads