Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass array by reference in golang

Tags:

arrays

go

I am from a C background and passing an array in C style causes an error.

package main
import "fmt"

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

func main(){
  var a [100]int
  a[1]=100
  f(a)
}

Error:: cannot use a (type [100]int) as type *int in argument to f

like image 938
iammehrabalam Avatar asked Aug 02 '16 22:08

iammehrabalam


Video Answer


2 Answers

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)
}
like image 65
jxstanford Avatar answered Sep 22 '22 00:09

jxstanford


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.

like image 28
Akshay Khot Avatar answered Sep 19 '22 00:09

Akshay Khot