How to pass an Array to a Function 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 which 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 syntax:
Syntax:
// For sized array
func function_name(variable_name [size]type){
// Code
}
// For unsized array
func function_name(variable_name []type){
// Code
}
Using these syntaxes you can pass 1 or multiple dimensional arrays to the function. Let us discuss this concept with the help of an example:
Example:
// 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 argumnet 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 accept 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.
Recommended Posts:
- How to pass a Slice to Function in Golang?
- Golang Pointer to an Array as Function Argument
- Function Arguments in Golang
- Function as a Field in Golang Structure
- main and init function in Golang
- How to Copy an Array into Another Array in Golang?
- Zero value in Golang
- Methods With Same Name in Golang
- Hello World in Golang
- Interfaces in Golang
- Slices in Golang
- Rune in Golang
- Structures in Golang
- Pointers in Golang
- Methods in Golang
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



