×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Language Passing Array to a Function

Last Updated : April 20, 2025

In Go, arrays can be passed to functions as arguments. However, when an array is passed to a function, it is passed by value, meaning a copy of the array is made. To modify the original array, a pointer or slice should be used.

Passing an Array by Value

By default, Go passes arrays by value, meaning that any modifications inside the function do not affect the original array.

Example

package main
import "fmt"

// Function to print an array
func printArray(arr [5]int) {
    for _, value := range arr {
        fmt.Print(value, " ")
    }
    fmt.Println()
}

func main() {
    numbers := [5]int{1, 2, 3, 4, 5}
    printArray(numbers)
}

When executed, this program outputs:

1 2 3 4 5 

Passing an Array by Reference

To modify the original array inside a function, a pointer to the array should be used.

Example

package main
import "fmt"

// Function to modify an array
func modifyArray(arr *[3]int) {
    arr[0] = 100 // Modifying the first element
}

func main() {
    numbers := [3]int{1, 2, 3}
    modifyArray(&numbers)
    fmt.Println(numbers)
}

When executed, this program outputs:

[100 2 3] 

Using Slices Instead of Arrays

Since slices are passed by reference, modifications made inside a function affect the original data.

Example

package main
import "fmt"

// Function to modify a slice
func modifySlice(s []int) {
    s[0] = 200 // Modifying the first element
}

func main() {
    numbers := []int{10, 20, 30}
    modifySlice(numbers)
    fmt.Println(numbers)
}

When executed, this program outputs:

[200 20 30] 

Go Passing Array to a Function Exercise

Select the correct option to complete each statement about passing arrays to functions in Go.

  1. When an array is passed to a function in Go, it is passed by ___.
  2. To allow a function to modify the original array, you should pass a ___ to the array.
  3. The correct way to define a function that accepts an array of 5 integers is ___.

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.