How to swap two slices in a byte array?

Viewed 232

I try to swap the slice 0:10 and the slice 10:20 using the following code. But

  data1 := make([]byte, 100)
  tmp := data1[0:10]
  data1[0:10] = data1[10:20]
  data1[10:20] = tmp 

But I got error messages like this.

../xxx.go:60:14: cannot assign to data1[0:10]
../xxx.go:61:15: cannot assign to data1[10:20]

Could anybody show me how to swap two slices in a byte array? Thanks.

2 Answers

You are trying to swap the contents of the underlying array. The only way of doing it is to swap individual elements:

for i := 0; i < 10; i++ {
    data[i], data[i+10] = data[i+10], data[i]
}

Or:

j := 10
for i := 0; i < 10; i++ {
    data[i], data[j] = data[j], data[i]
    j++
}

@BurakSerdar 's answer is the most efficient for the small chunks of data to move and the swap nature of the operation.

If you're curious how to copy sections of a slice, simply use the internal copy function:

copy(data[0:10], data[10:20]) // overwrites first 10-bytes with next 10 bytes

To perform a swap with copy is a little awkward, but if you're curious:

// tmp := data[0:10] // will *NOT* work
//                   // as `tmp` will just reference data's underlying byte-array

tmp := make([]byte, 10) // need fresh memory
copy(tmp, data[0:10])

copy(data[0:10], data[10:20])

copy(data[10:20], tmp)

https://play.golang.org/p/ud31Gxfa19b

Related