Logo

Programming-Idioms

History of Idiom 28 > diff from v88 to v89

Edit summary for version 89 by programming-idioms.org:
[Go] Go 1.21

Version 88

2023-08-17, 12:03:37

Version 89

2023-08-17, 12:05:29

Idiom #28 Sort by a property

Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.

Idiom #28 Sort by a property

Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.

Variables
items,p
Variables
items,p
Imports
import "slices"
import "cmp"
Imports
import "slices"
import "cmp"
Code
less := func(a, b Item) int {
	return cmp.Compare(a.p, b.p)
}
slices.SortFunc(items, less)
Code
compare := func(a, b Item) int {
	return cmp.Compare(a.p, b.p)
}
slices.SortFunc(items, compare)
Comments bubble
SortFunc is generic and type-safe at compile time.
Comments bubble
SortFunc is generic and type-safe at compile time.
Doc URL
https://pkg.go.dev/slices#SortFunc
Doc URL
https://pkg.go.dev/slices#SortFunc
Demo URL
https://go.dev/play/p/cHDoZAwRMCT
Demo URL
https://go.dev/play/p/arW9Dcs_6mH