How to work around Go array sizes in functions

huangapple go评论138阅读模式
英文:

How to work around Go array sizes in functions

问题

我刚开始使用Go语言,有一件让我感到紧张的事情是,如果我定义了一个接受数组的函数,然后将一个具有特定大小的数组传递给一个函数,VS Code会报错。

例如,我有如下代码:

  1. func cmplt(a, b []uint64) uint64 {
  2. var r, m, i uint64
  3. r = 0
  4. m = 0
  5. for i = 2; i >= 0; i-- {
  6. r |= LtUint64(a[i], b[i]) & ^m
  7. m |= MaskUint64(NeUint64(a[i], b[i]))
  8. }
  9. return r & 1
  10. }
  11. func singleSample(in []uint64) uint64 {
  12. var i, index uint64
  13. index = 0
  14. for i = 0; i < 52; i++ {
  15. index = SelectUint64(index, i+1, cmplt(in, table[i]))
  16. }
  17. return index
  18. }

其中table的类型是[52][3]uint64。我收到一个错误消息,内容是:cannot use table (type [3]uint64) as []uint64 in argument to cmplt

在Go语言中,有没有办法绕过这个问题,而不是在函数参数中具体指定数组的大小?

英文:

I just started using Go, and one thing that makes me nervous is that if I define a function that accepts an array, and then pass an array to a function with a specific size, VS Code complains about it.

For example, I have something like this:

  1. func cmplt(a, b []uint64) uint64 {
  2. var r, m, i uint64
  3. r = 0
  4. m = 0
  5. for i = 2; i &gt;= 0; i-- {
  6. r |= LtUint64(a[i], b[i]) &amp; ^m
  7. m |= MaskUint64(NeUint64(a[i], b[i]))
  8. }
  9. return r &amp; 1
  10. }

And then I call this function inside another function as:

  1. func singleSample(in []uint64) uint64 {
  2. var i, index uint64
  3. index = 0
  4. for i = 0; i &lt; 52; i++ {
  5. index = SelectUint64(index, i+1, cmplt(in, table[i]))
  6. }
  7. return index
  8. }

where table has type [52][3]uint64. I get an error message saying: cannot use table (type [3]uint64) as []uint64 in argument to cmplt.

Is there any way in Go to workaround this, instead of specifically specifying the array size in function parameter?

答案1

得分: 3

你的 cmplt 函数期望接收一个 uint64 切片,而不是一个包含3个元素的数组。通过对 table[i] 进行切片操作可以修复这个错误:

  1. cmplt(in, table[i][:])
英文:

Your cmplt is expecting a uint64 slice, and not a 3 element array. Taking a slice of table[i] will fix the error:

  1. cmplt(in, table[i][:])

答案2

得分: 0

从我看到的情况来看,最好的解决方案是将你的cmplt函数定义更改为接受数组:

func cmplt(a, b [3]uint64) uint64 {

在你的代码中,你无论如何都依赖于底层数组的大小,因此请确保尽可能清楚地指定函数的依赖关系。

英文:

From what I see the best solution is to change your cmplt function definition to accept arrays:

func cmplt(a, b [3]uint64) uint64 {

In your code you any way rely on the size of the underlying array, hence make sure to specify your function dependencies as clear as possible

huangapple
  • 本文由 发表于 2017年6月11日 19:39:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/44483409.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定