English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statements

Golang Functions & Methods

Golang Structs

Golang Slices & Arrays

Golang Strings(String)

Golang Pointers

Golang Interfaces

Golang Concurrency

Golang Exceptions(Error)

Miscellaneous Golang

Go Array as Function Parameter

Arrays in the Go programming language are very similar to other programming languages. In programs, sometimes we need to store a set of data of the same type, such as a list of student grades. This type of collection is stored in the program using arrays. An array is a fixed-length sequence used to store elements of the same type in memory.
In the Go programming language, you are allowed to pass arrays as parameters in functions. To pass an array as a parameter in a function, you must first use the following syntax to create formal parameters:

Syntax:

//For arrays of specified size
func function_name(variable_name [size]type){
// Code
}
//For arrays without a size
func function_name(variable_name []type){
// Code
}

Using this syntax, you can pass1or multidimensional arrays to the function. Let's discuss this concept with an example:

//an array as a parameter for a function.
package main
import \
//This function accepts
//Pass the array as a parameter
func myfun(a [6int, size int) int {
    var k, val, r int
    for k = 0; k < size; k++ {
        val += a[k]
    }
    r = val / size
    return r
}
func main() {
    //Create and initialize an array
    var arr = [6int{67, 59, 29, 35, 4, 34}
    var res int
    //pass the array as a parameter
    res = myfun(arr, 6)
    fmt.Printf("The final result is: %d ", res)
}

Output:

The final result is: 38

Usage explanation:In the above example, we have a function namedmyfun()a function that accepts an array as a parameter. In the main function, we will use int typearr [6]Pass an array-sized function that returns the average of the array.