How to pass an array to a function in Golang

In Go, arrays are used to store a fixed-length collection of data of the same type. To manage this data efficiently, you often need to pass arrays to functions. In this article, we will learn how to pass arrays to functions in Golang .

 

How to pass an array to a function in Golang Picture 1

For example:

package main import "fmt" // Hàm tính trung bình của một mảng func calculateAverage(arr [6]int, size int) int { var sum int for _, value := range arr { sum += value } return sum / size } func main() { scores := [6]int{67, 59, 29, 35, 4, 34} average := calculateAverage(scores, len(scores)) fmt.Printf("%dn", average) }

Result:

38

Detailed explanation of how to pass array to function in Golang

In this example, the calculateAverage() function takes an array of integers and its size as arguments. It calculates the average of the array elements and returns that value. The main function initializes an array named scores and calls the function that calculates the average.

Key points:

Array declaration:

Use the syntax var arrayName [size]type to declare an array.

 

var numbers [5]int // Một mảng gồm 5 số nguyên

Passing arrays:

In Go, arrays are passed to functions by value, meaning the function receives a copy of the array. Changes made inside the function do not affect the original array.

Pointer to modify the original array:

If you want to modify the original array, you should pass a pointer to it.

func modifyArray(arr *[5]int) { for i := range arr { arr[i] += 10 // Tăng mỗi phần tử lên 10 } }

Modifying an array in Golang

For example:

package main import "fmt" // Hàm tăng mỗi phần tử của mảng này func incrementArray(arr *[5]int) { for i := range arr { arr[i]++ // Increment each element by 1 } } func main() { values := [5]int{1, 2, 3, 4, 5} // Chỉnh sửa mảng incrementArray(&values) fmt.Println("Incremented array:", values) }

Result:

Mảng tăng dần: [2 3 4 5 6]

Passing arrays to functions in Go allows efficient data management. Understanding how to pass and modify arrays will help you write efficient Go programs.

4 ★ | 2 Vote

May be interested