Go Slice Sorting: Difference between revisions
Jump to navigation
Jump to search
(Created page with "=Internal= * Go Package <tt>sort</tt> =Overview=") |
|||
Line 2: | Line 2: | ||
* [[Go_Package_sort#Slice_Sorting|Go Package <tt>sort</tt>]] | * [[Go_Package_sort#Slice_Sorting|Go Package <tt>sort</tt>]] | ||
=Overview= | =Overview= | ||
The <code>slices</code> package comes with slice sorting functionality. | |||
=Sorting Based on a Comparison Function= | |||
<code>slices.SortFunc(slice []SomeType, func(a, b SomeType) int)</code> 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. | |||
<syntaxhighlight lang='go'> | |||
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" | |||
</syntaxhighlight> |
Latest revision as of 03:21, 13 June 2024
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"