The Wayback Machine - https://web.archive.org/web/20241001035334/https://www.geeksforgeeks.org/how-to-pass-an-array-to-a-function-in-golang/
Open In App

How to pass an Array to a Function in Golang?

Last Updated : 02 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Previous Article
Next Article

Similar Reads

How to pass a Slice to Function in Golang?
Slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. It is just like an array having an index value and length, but the size of the slice is resized they are not in fixed-size just like an array. In Go language, you are allowed to pass a slice to a fu
3 min read
Golang Pointer to an Array as Function Argument
Prerequisite: Pointers in Golang Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Whereas an array is a fixed-length sequence which is used to store homogeneous elements in the memory. You can use the pointers to an array and pass that one as an argument to the function. To u
3 min read
How to Copy an Array into Another Array in Golang?
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 t
4 min read
Copy an Array by Value and Reference into Another Array in Golang
Array in Golang is a numbered sequence of elements of the same type. The size of the array is fixed. We can access the elements by their index. You can declare an array of size n and type T specifying this way mentioned below. var array[n]T Go doesn't have an inbuilt function to copy an array to another array. There are two ways of copying an array
2 min read
math.Lgamma() Function in Golang with Examples
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. This package provides Lgamma() function which is used to find the natural logarithm and sign (either -1 or +1) of Gamma(a). So, you need to add a math package in your program with the help of th
2 min read
math.Float64bits() Function in Golang With Examples
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. This package provides Float64bits() function which returns the IEEE 754 binary representation of a with the sign bit of a and the result in the same bit position. So, you need to add a math pack
2 min read
atomic.AddInt64() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The AddInt64() function in Go language is used to automatically add delta to the *addr. This function is defined under the atomic package. Here, you need to import "sync/atomic" package in order to use these functions. Syntax
3 min read
atomic.StoreInt64() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The StoreInt64() function in Go language is used to atomically store val into *addr. This function is defined under the atomic package. Here, you need to import "sync/atomic" package in order to use these functions. Syntax: f
2 min read
reflect.FieldByIndex() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.FieldByIndex() Function in Golang is used to get the nested field corresponding to index. To access this function, one needs to imports the reflect package in the
2 min read
strings.Contains Function in Golang with Examples
strings.Contains Function in Golang is used to check the given letters present in the given string or not. If the letter is present in the given string, then it will return true, otherwise, return false. Syntax: func Contains(str, substr string) bool Here, str is the original string and substr is the string that you want to check. Let us discuss th
2 min read
bits.Sub() Function in Golang with Examples
The bits.Sub() Function in Golang is used to find the difference of a, b and borrow, i.e. diff = a - b - borrow. Here the borrow must be 0 or 1; otherwise, the behavior is undefined. To access this function, one needs to imports the math/bits package in the program. The return value of the borrowOutput will be always 0 or 1 in any case. Syntax: fun
2 min read
io.PipeWriter.CloseWithError() Function in Golang with Examples
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The PipeWriter.CloseWithError() function in Go language is used to close the writer. However, successive reads from the PipeReader i.e, read half of the pipe will not return any
3 min read
time.Round() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Round() function in Go language is used to find the outcome of rounding the stated duration 'd' to the closest multiple of 'm' duration. Here, the rounding manner for middle values is to round far off from 0. Moreover, this function is defined under th
2 min read
reflect.AppendSlice() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.AppendSlice() Function in Golang is used to appends a slice t to a slice s. To access this function, one needs to imports the reflect package in the program. Synta
2 min read
reflect.ChanOf() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.ChanOf() Function in Golang is used to get the channel type with the given direction and element type, i.e., t represents int, ChanOf(RecvDir, t) represents <-c
1 min read
flag.Bool() Function in Golang With Examples
Go language provides inbuilt support for command-line parsing and has functions that could be used to define flags to be used with a command-line program using the flag package. This package provides the flag.Bool() function which is used to define a boolean flag with the specified name, default value, and usage string. Syntax: func Bool(name strin
2 min read
time.Sleep() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Sleep() function in Go language is used to stop the latest go-routine for at least the stated duration d. And a negative or zero duration of sleep will cause this method to return instantly. Moreover, this function is defined under the time package. He
3 min read
time.Time.Year() Function in Golang with Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Year() function in Go language is used to find the year in which the specified "t" happens. Moreover, this function is defined under the time package. Here, you need to import the "time" package in order to use these functions. Syntax: func (t Tim
2 min read
reflect.DeepEqual() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.DeepEqual() Function in Golang is used to check whether x and y are “deeply equal” or not. To access this function, one needs to imports the reflect package in the
2 min read
reflect.Indirect() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Indirect() Function in Golang is used to get the value that v points to, i.e., If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirec
2 min read
reflect.CanAddr() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.CanAddr() Function in Golang is used to check whether the value's address can be obtained with Addr. To access this function, one needs to imports the reflect pack
2 min read
reflect.CanInterface() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.CanAddr() Function in Golang is used to check whether Interface can be used without panicking. To access this function, one needs to imports the reflect package in
1 min read
reflect.CanSet() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.CanSet() Function in Golang is used to check whether the value of v can be changed. To access this function, one needs to imports the reflect package in the progra
2 min read
reflect.Cap() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Cap() Function in Golang is used to get the v's capacity. To access this function, one needs to imports the reflect package in the program. Syntax: func (v Value)
1 min read
Function Arguments in Golang
A function in Golang is a collection of statements which is used to perform specific task and return the result to the caller. A function can also perform some specific task without returning anything. Golang supports two different ways to pass arguments to the function i.e. Pass by Value or Call by Value and Pass By Reference or Call By Reference.
4 min read
Function as a Field in Golang Structure
A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct. As we know that in Go language function is also a user-defined type so, you are allowed to create a function fie
2 min read
Higher-Order Function in Golang
In Go, language, a function is called a Higher-Order Function if it fulfills one of the following conditions:1. Passing Functions as an Argument to Another Function:If a function is passed as an argument to another function, then such types of functions are known as a Higher-Order function. This passing function as an argument is also known as a ca
2 min read
strings.ContainsRune() Function in Golang with Examples
The Unicode, which is a superset of ASCII and contains all the characters present in the world's writing system, is the character set that's being followed right now. Each character in the Unicode system is uniquely identified by a Unicode code point, which is referred to as runes in Golang. To know more about runes please go through the article Ru
2 min read
atomic.LoadInt64() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The LoadInt64() function in Go language is used to atomically loads *addr. This function is defined under the atomic package. Here, you need to import "sync/atomic" package in order to use these functions. Syntax: func LoadIn
2 min read
reflect.Index() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Index() Function in Golang is used to get the v's i'th element. To access this function, one needs to imports the reflect package in the program. Syntax: func (v V
2 min read