6

I want to write a function that can accept arrays of fixed length, but different arrays have different lengths.

I know that i can pass the slice with arr[:] (the function will accept []T), but is there another way, maybe more efficient?

I'm using a struct that i'd like to mantain with fixed length arrays (for documentation purposes), so using slices everywhere at declaration time is not optimal for my purpose.

Blallo
  • 450
  • 3
  • 11
  • 3
    Just use slice, array is not suitable to be passed as param, it will make a copy, waste space & time, also there are two copy of undering data. – Eric Aug 08 '18 at 09:52
  • 1
    This answer https://stackoverflow.com/questions/48849493/go-variadic-function-argument-passing/48849643#48849643 might be of help. – Himanshu Aug 08 '18 at 09:58
  • 1
    Slicing an array is not inefficient at all. See https://blog.golang.org/slices. – Peter Aug 08 '18 at 10:29

1 Answers1

6

No there is no way to pass different size arrays, because the length of an array is part of the type.

For example [3]int is a different type then [2]int.

At all in Go it is not recommended to use arrays you should use slices (https://golang.org/doc/effective_go.html#arrays).

apxp
  • 5,240
  • 4
  • 23
  • 43
  • 5
    Another reason not to use array is, when pass array as param, it will make a copy, anyway this won't work. – Eric Aug 08 '18 at 09:54