Home > other >  Golang subslice with no numbers as a function arg
Golang subslice with no numbers as a function arg

Time:08-05

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?

CodePudding user response:

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 .

CodePudding user response:

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 .

  • Related