Go Slice Sorting

From NovaOrdis Knowledge Base
Revision as of 03:21, 13 June 2024 by Ovidiu (talk | contribs) (→‎Overview)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Internal

Overview

The slices package comes with slice sorting functionality.

Sorting Based on a Comparison Function

slices.SortFunc(slice []SomeType, func(a, b SomeType) int) takes the typed slice and a function that expects two type instances, a and b in order, and that should return a negative value if a < b, zero if a == b and a positive value if a > b.

import (
	"slices"
	"time"
)

type SomeType struct {
	created time.Time
	color   string
}

...
t0 := time.Now()
// listed in the rough inverse order of creation time
s := []SomeType{
	{
		created: t0.Add(10 * time.Second),
		color:   "red",
	},
	{
		created: t0.Add(5 * time.Second),
		color:   "gray",
	},
	{
		created: t0,
		color:   "white",
	},
	{
		created: t0.Add(5 * time.Second),
		color:   "gray 2",
	},
}

slices.SortFunc(s, func(a, b SomeType) int {
	return int(a.created.Sub(b.created))
})

// the ordered slice is "white", "gray", "gray 2", "red"