« Back to Index

Go: Sorting

View original Gist on GitHub

Tags: #go

same as sort.Ints.go

// We already have sort.Ints() so this is a redundant implementation.

package main

import (
	"fmt"
	"sort"
)

type items []int

func (i items) Len() int {
	return len(i)
}

func (i items) Less(a, b int) bool {
	return i[a] < i[b]
}

func (i items) Swap(a, b int) {
	i[a], i[b] = i[b], i[a]
}

func main() {
	i := []int{25, 1, 10, 5, 4, 7}
	sort.Sort(items(i))
	fmt.Println(i)
}

sort slice of strings by length of each string.go

package main

import (
	"fmt"
	"sort"
)

type items []string

func (i items) Len() int {
	return len(i)
}

func (i items) Less(a, b int) bool {
	return len(i[a]) < len(i[b])
}

func (i items) Swap(a, b int) {
	i[a], i[b] = i[b], i[a]
}

func main() {
	i := []string{"peach", "banana", "kiwi"}
	sort.Sort(items(i))
	fmt.Println(i)
}

sort.Slice a slice of structs by string field.go

// In this example I want the 'default' starter kit to be first in the list.
// We can't use the greater-than > operator on a bool type so we have to convert to int.

package main

import (
	"fmt"
	"sort"
	"strings"
)

type StarterKits struct {
	Path string
}

func main() {
	kits := []StarterKits{
		{Path: "https://github.com/fastly/compute-starter-kit-rust-beacon-termination"},
		{Path: "https://github.com/fastly/compute-starter-kit-rust-static-content"},
		{Path: "https://github.com/fastly/compute-starter-kit-rust-default"},
	}
	sort.Slice(kits, func(i, j int) bool {
		suffix := "rust-default"
		a := strings.HasSuffix(kits[i].Path, suffix)
		b := strings.HasSuffix(kits[j].Path, suffix)
		var (
			bitSetA int8
			bitSetB int8
		)
		if a {
			bitSetA = 1
		}
		if b {
			bitSetB = 1
		}
		fmt.Println(bitSetA, bitSetB)
		return bitSetA > bitSetB
	})
	fmt.Println(kits)
}