doufu9836
2018-05-16 11:55
浏览 530
已采纳

接受任意大小的数组作为参数的函数(在Golang中可以吗?)

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

e.g.,

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).

Regards

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.

图片转代码服务由CSDN问答提供 功能建议

Q:在golang中,有没有一种方法可以定义一个接受任意长度数组的函数 作为参数?</ strong> </ p>

例如</ p>

 函数demoArrayMagic(arr [magic] int){
 ....  
} 
 </ code> </ pre> 
 
 

我了解到,在golang中,数组长度是变量类型的一部分,因此,以下函数不会接受一个任意数组 作为输入</ p>

 函数demoArray(arr [2] int){
 .... 
} 
 </ code> </ pre> 
 
 <  p>该函数不会使用 arrInput [6] int </ code>作为输入进行编译-即, demoArray(arrInput)</ code>将无法编译。  </ p> 
 
 

以下接受切片参数的函数也不接受数组作为参数(不同类型,如预期):</ p>

  函数demoSlice(arr [] int){
 .... 
} 
 </ code> </ pre> 
 
 

即, demoSlice(arrInput)</ code>不 </ p>

问题是,有没有一种方法可以定义一个函数,该函数采用任意长度的数组(数组,不是切片)? </ p>

这个问题看起来很奇怪,并且限制了语言的施加。</ p>

这个问题与动机无关,但还是有道理的,但就我而言,其原因如下。 我有一组函数以类型为 [] [] int </ code>的数据结构作为参数。 我注意到,它们的GOB序列化(MB / s)速度比我拥有的其他数据结构慢10倍。 我想这可能与片中的取消引用操作链有关。 从切片到数组(即定义 [10000] [128] int </ code>类型的对象)可能会改善情况(希望如此)。 </ p>

注意</ p>

Ps:</ strong>:我现在提醒一下,Go可以“按值”传递/使用事物,使用数组可能 过度杀伤,因为golang将复制很多次。 我认为我将继续学习切片</ strong>,并且我将尝试了解一下GOB的内部原理。</ p> </ div>

1条回答 默认 最新

相关推荐 更多相似问题