0

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

zening.chen
  • 111
  • 8
  • 3
    One cannot pass an array without defining size. For such cases one needs to use slices.Use of arrays is very limited in GoLang. – nilsocket Jul 07 '19 at 13:00
  • 1
    Possible duplicate of [Why can't you put a variable as a multidimensional array size in Go?](https://stackoverflow.com/questions/46809499/why-cant-you-put-a-variable-as-a-multidimensional-array-size-in-go/46809576?r=SearchResults#46809576) – icza Jul 07 '19 at 13:53
  • Do you want something like that? https://play.golang.org/p/Tko8AP36ukH – Anton Ohorodnyk Jul 07 '19 at 20:20

1 Answers1

3

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

colm.anseo
  • 19,337
  • 4
  • 43
  • 52