doufu9836 2018-05-16 11:55
浏览 534


Q: Is there a way, in golang, to define a function which accepts an array of arbitrary length as argument?


function demoArrayMagic(arr [magic]int){

I have understood that in golang, array length is part of the variable type, for this reason the following function is not going to accept one arbitrary array as input

function demoArray(arr [2]int){

This function is not going to compile with arrInput [6]int as input--i.e., demoArray(arrInput) will fail to compile.

Also the following function, which accepts a slice argument, does not accept arrays as arguments (different types, as expected):

function demoSlice(arr []int){

i.e., demoSlice(arrInput) does not compile, expects a slice not an array.

The question is, is there a way to define a function that takes arrays of arbitrary length (arrays, NOT slice)? It looks quite strange and limiting for a language to impose this constraint.

The question makes sense independently from the motivation, but, in my case, the reason behind is the following. I have a set of functions which takes as arguments data structures of type [][]int. I noticed that GOB serialization for them is 10x slower (MB/s) than other data structures I have. I suppose that may be related to the chain of derefencing operations in slices. Moving from slices to array--i.e.,defining objects of type [10000][128]int--may improve situation (I hope).


P.s: I remind now that Go, passes/uses things 'by value', using arrays may be overkill cause golang is going to copy them lot of times. I think I'll stay with slices and I'll try to understand GOB internals a bit.

  • 写回答

1条回答 默认 最新

  • dongsheng1238 2018-05-16 11:58

    There is not. Go does not support generics.

    The only way would be to use interface{}, but that would allow to pass a value of any type, not just arrays of your desired type.

    Arrays in Go are "secondary". The solution is to use slices for your requirement.

    One thing to note here is that you may continue to use arrays, and only slice them when you want to pass them to this function, e.g.:

    func main() {
        a1 := [1]int{1}
        a2 := [2]int{1, 2}
    func demo(s []int) {
        fmt.Println("Passed:", s)

    Output of the above (try it on the Go Playground):

    Passed: [1]
    Passed: [1 2]
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 python提取.csv文件中的链接会经常出现爬取失败
  • ¥15 数据结构中的数组地址问题
  • ¥15 maya的mel里,怎样先选择模型A,然后利用mel脚本自动选择有相同名字的模型B呢。
  • ¥15 Python题,根本不会啊
  • ¥15 会会信号与系统和python的来
  • ¥15 关于#python#的问题
  • ¥20 oracle RAC 怎么配置啊,配置
  • ¥15 excel 日常使用中出现问题
  • ¥20 pdusession建立失败
  • ¥15 为什么mqtt接收不到数据?