Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Passing Arrays into Functions | Arrays and Slices
Introduction to GoLang
course content

Conteúdo do Curso

Introduction to GoLang

Introduction to GoLang

1. Getting Started
2. Data Types
3. Control Structures
4. Functions
5. Arrays and Slices
6. Intro to Structs & Maps

bookPassing Arrays into Functions

A valuable feature is the ability to pass arrays into functions so that we can use these arrays within other scopes, especially when they are locally declared.

The general syntax for an array argument in a function is as follows:

Implementing this in a function would look something like this:

go

index

copy
123
func myFunc(arr [5] int) { // code here }

The following example demonstrates passing an array into a function and using it:

go

index

copy
123456789101112131415
package main import "fmt" func sumOfAll(arr [10] int) int { total := 0 for i := 0; i < 10; i++ { total += arr[i] } return total } func main() { var numbers = [10] int { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 } fmt.Printf("Sum: %d", sumOfAll(numbers)) }

In Go (Golang), arrays are always passed by value into functions. This means that when we pass an array into a function, a local copy of the original array is created inside the function. Consequently, any modifications made to the array inside the function won't impact the original array because the data being accessed inside the function is a copy of the original array.

The following program illustrates that making changes to the array within the function does not affect the original array:

go

index

copy
12345678910111213
package main import "fmt" func myFunc(nums [3] int) { nums[1] = 10 } func main() { var values = [3] int {1, 2, 3} fmt.Println("Before:", values) myFunc(values) fmt.Println("After: ", values) }

Note

In contrast to passing by value, there's the concept of passing by reference, where a reference to the array or variable is passed into the function. Consequently, modifying the value inside the function also modifies the source. In some programming languages, arrays are passed by reference by default.

What is the appropriate code for the parameter of the `myFunc` function:

What is the appropriate code for the parameter of the myFunc function:

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 5. Capítulo 8
some-alt