Created
September 7, 2016 21:37
-
-
Save schmohlio/615ab4d47bc01020786ef58aec622fdf to your computer and use it in GitHub Desktop.
sort byte slices in Golang without needing to fmt as string. useful for Set hashes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"log" | |
"sort" | |
) | |
// implement `Interface` in sort package. | |
type sortByteArrays [][]byte | |
func (b sortByteArrays) Len() int { | |
return len(b) | |
} | |
func (b sortByteArrays) Less(i, j int) bool { | |
// bytes package already implements Comparable for []byte. | |
switch bytes.Compare(b[i], b[j]) { | |
case -1: | |
return true | |
case 0, 1: | |
return false | |
default: | |
log.Panic("not fail-able with `bytes.Comparable` bounded [-1, 1].") | |
return false | |
} | |
} | |
func (b sortByteArrays) Swap(i, j int) { | |
b[j], b[i] = b[i], b[j] | |
} | |
// Public | |
func SortByteArrays(src [][]byte) [][]byte { | |
sorted := sortByteArrays(src) | |
sort.Sort(sorted) | |
return sorted | |
} |
I think this entire code sample can be replaced with this:
func SortByteArrays(src [][]byte) {
sort.Slice(src, func(i, j int) bool { return bytes.Compare(src[i], src[j]) < 0 })
}
(I think it's better to not return the sorted array, because it implies you didn't modify src
, but of course you did --- src
has been overwritten by the sorted array, in your implementation and in mine.)
-Ken
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Less could be shortened to: