Sort Byte Array

How can I sort *[]Byte?

I was trying to use the following function but it’s not working fine.

sort.Slice(src, func(i, j int) bool { return bytes.Compare((*src)[i], (*src)[j]) < 0 })

Getting this error: cannot use (*src)[i] (variable of type byte) as []byte value in argument to bytes.Comparecompiler

Any suggestion?

The signature of bytes.Compare is:

func Compare(a, b []byte) int

So it doesn’t compare individual bytes, it compares slices of bytes.

Instead of using it in your less function, just compare the byte values:

sort.Slice(src, func(i, j int) bool { return (*src)[i] < (*src)[j]) })
1 Like