Golang子切片作为函数参数时不带数字

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

Golang subslice with no numbers as a function arg

问题

最近我遇到了一些看起来像这样的代码:

x := bytes.IndexByte(data[:], 1)

当我删除冒号后,它似乎完全相同地工作,冒号有什么作用吗?

英文:

I recently came across some code that looked like this

x := bytes.IndexByte(data[:], 1)

and upon removing the colon it seemed to work exactly the same, is there a purpose to the colon?

答案1

得分: 2

在Go语言中,数组和切片是有区别的。每个切片都与一个数组相关联,可以是显式地或隐式地关联,并且切片引用数组的一段元素。例如,

x := [4]byte{0, 1, 2, 3}

定义了一个包含四个字节的数组。由于bytes.IndexByte()需要一个切片(而不是数组)作为其第一个参数,尝试写bytes.IndexByte(x, 1)会导致错误消息cannot use x (variable of type [4]byte) as type []byte in argument to bytes.IndexByte。为了解决这个问题,我们需要定义一个引用x元素的切片。可以通过写x[0:4]或者更简洁地写x[:]来实现。因此,在这里正确调用bytes.IndexByte()的方式是

bytes.IndexByte(x[:], 1)

你说在你的代码中去掉[:]没有任何区别。这表明你的代码中的data已经是一个切片。在这种情况下,data和"子切片"data[:]是相同的,所以没有理由用data[:]代替data

这里有一些代码来说明这些观点:https://go.dev/play/p/yma1krRdNML。

英文:

In Go there is a difference between arrays and slices. Every slice is tied to an array, either explicitly or implicitly, and the slice references a range of elements of the array. For example,

x := [4]byte{0, 1, 2, 3}

defines an array of four bytes. Since bytes.IndexByte() needs a slice (not an array) as its first argument, attempting to write bytes.IndexByte(x, 1) results in the error message cannot use x (variable of type [4]byte) as type []byte in argument to bytes.IndexByte. To fix this, we need to define a slice which references the elements of x. This can be done by writing x[0:4] or, shorter, x[:]. Thus, the correct call of bytes.IndexByte() here would be

bytes.IndexByte(x[:], 1)

You say that in your case removing the [:] made no difference. This indicates that data in your code already is a slice. In this case, data and the "sub-slice" data[:] are identical and there would be no reason to write data[:] instead of data.

Some code to illustrate these points is at https://go.dev/play/p/yma1krRdNML .

答案2

得分: -3

在Golang中,x[:]表示x的存储。所以x[:]==x。如果输入值已经是切片,则不会产生影响,否则需要将数组转换为切片。

英文:

In Golang , x[:] refers to the storage of x. so x[:]==x only .If input value is already slice then it should not effect , otherwise it is required to convert array into a slice .

huangapple
  • 本文由 发表于 2022年8月4日 08:26:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/73229137.html
匿名

发表评论

匿名网友

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

确定