pass array by reference in golang

As others have mentioned in comments, you probably want to use a slice rather than an array. Slices are passed by reference already, so no need to specify pointers. The make statement below creates a slice of ints (backed by an array). In the code below, I gave it a length of 2 and a capacity of 100 in order to satisfy your goal of assigning to index 1.

import (
    "fmt"
)

func f(a []int) {
    fmt.Println(a[1])
}

func main() {
    a := make([]int, 2, 100)
    a[1] = 100
    f(a)
}

To answer the original question, you can pass a pointer to the array, to pass the array by reference.

For example, the following function changes the contents of an array of 3 integers.

func change(ptr *[3]int) {
    ptr[2] = 20
}

You can call this by passing a pointer to the original array:

change(&arr)

Complete Example:

package main

import (
    "fmt"
)

func main() {
    grades := [3]int {1, 2, 3}

    fmt.Printf("\nOriginal array:\n")
    for i, v := range grades {
        fmt.Printf("arr[%d] = %d\n", i, v)    // prints 1 2 3
    }

    change(&grades)
    fmt.Printf("\nModified grades:\n")
    for i, v := range grades {
        fmt.Printf("arr[%d] = %d\n", i, v)    // prints 1 2 20
    }
}

func change(ptr*[3]int) {
    ptr[2] = 20
}

In your example, f is expecting a pointer to an integer,

func f(a *int)    // a points to an integer

and you are passing it an array,

var a [100]int
f(a)

hence it gives you the error cannot use a (type [100]int) as type *int in argument to f.

Although passing a pointer to an array is efficient and allows the called function to change the caller’s variable, arrays are still fixed in size. Hence, slices are recommended, which are passed by reference and are dynamic in size.


you must use a slice instead of an array as argument of function. for example:

func p(a int){
fmt.Println(a)
}
func main() {
    var a = make([]int,2,10) //2 is length, 10 is capacity
    a[0] = 10
    p(a[0])
}

array is value type, slice is reference type. you can see more at https://blog.golang.org/go-slices-usage-and-internals

Wish it help you!

Tags:

Arrays

Go