Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

How to Pass an Array to a Function in Go

Use a fixed-length array, an array pointer or a slice in a Go function. See which forms copy values and which can change the original.

Table of Contents

In Go, use [N]T to pass a fixed-length array by value, *[N]T to pass a pointer to that array, or []T to accept a slice of any length. An array parameter copies the array. A pointer or a slice lets a function change the elements it refers to.

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

Pass a fixed-length array by value

The length is part of the array type. A function defined for [6]int cannot accept a [5]int. Use len inside the function. This example converts the total and length to float64 so the quotient keeps its fractional part.

package main

import "fmt"

func average(scores [6]int) float64 {
    sum := 0
    for _, score := range scores {
        sum += score
    }
    return float64(sum) / float64(len(scores))
}

func main() {
    scores := [6]int{67, 59, 29, 35, 4, 34}
    fmt.Printf("%.2fn", average(scores)) // 38.00
}

Pass a pointer to change the original array

Use &values to pass the address of the array. Go allows range and indexed access directly on a pointer to an array.

func increment(values *[5]int) {
    for i := range values {
        values[i]++
    }
}

// Inside main:
values := [5]int{1, 2, 3, 4, 5}
increment(&values)
fmt.Println(values) // [2 3 4 5 6]

Use a slice when the length can vary

A slice parameter can accept values from arrays of different lengths. Call it with values[:] to use the existing array’s storage. Assigning to a slice element updates that storage. If the function appends to the slice and the caller needs the resulting length or storage, return the updated slice.

func incrementAll(values []int) {
    for i := range values {
        values[i]++
    }
}

// Inside main, given an array named values:
incrementAll(values[:])

For details on types and shared storage, see the Go language specification.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.