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

Golang Basic Tutorial

Golang Control Statements

Golang Function & Method

Golang Struct

Golang Slice & Array

Golang String(String)

Golang Pointer

Golang Interface

Golang Concurrency

Golang Exception(Error)

Miscellaneous Golang

Go Array as Function Parameter

Arrays in the Go programming language are very similar to other programming languages. In programs, we sometimes 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 size
func function_name(variable_name []type){
// Code
}

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

//Array as a function parameter
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 namedmyfun()function that accepts an array as a parameter. In the main function, we will pass an int typearr [6]Pass an array-sized function that returns the average of the array.