zening.chen
zening.chen

Reputation: 127

How to pass array to a GO function without define the size of the array?

I try to defined an array pass it to the function that doesn't define the size of the argument, errors occur however.

package main

import "fmt"

func main() {
    var a=[5]int{1,2,3,4,5}
    f(a,5)
    fmt.Println(a)
}
func f(arr []int,size int) {
    for i,x:=range arr  {
        fmt.Println(i,x)
        arr[i]=100
    }
}

cannot use a (type [5]int) as type []int in argument to f

Upvotes: 0

Views: 2149

Answers (1)

colm.anseo
colm.anseo

Reputation: 22147

You can convert the array to a slice inline, like so:

f(a[:],5)

Playground

For more background see: https://blog.golang.org/go-slices-usage-and-internals

Upvotes: 3

Related Questions