Documentation
¶
Overview ¶
Package natural defines a natural "less" to compare two strings while interpreting natural numbers.
This is occasionally nicknamed 'natsort'.
It does so with no memory allocation.
Example ¶
package main
import (
"fmt"
"slices"
"strings"
"github.com/maruel/natural"
)
func main() {
items := []string{
"gpio10",
"gpio1",
"gpio20",
}
slices.SortFunc(items, natural.Compare)
fmt.Println(strings.Join(items, "\n"))
}
Output: gpio1 gpio10 gpio20
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Compare ¶ added in v1.2.0
Compare does a 'natural' comparison on the two strings.
It treats digits as decimal numbers, so that Compare("10", "2") return >0.
This function does no memory allocation.
Example ¶
package main
import (
"fmt"
"slices"
"strings"
"github.com/maruel/natural"
)
func main() {
items := []string{
"gpio10",
"gpio1",
"gpio20",
}
slices.SortFunc(items, natural.Compare)
fmt.Println(strings.Join(items, "\n"))
}
Output: gpio1 gpio10 gpio20
func Less ¶
Less does a 'natural' comparison on the two strings.
It treats digits as decimal numbers, so that Less("10", "2") return false.
This function does no memory allocation.
Example ¶
package main
import (
"fmt"
"sort"
"strings"
"github.com/maruel/natural"
)
func main() {
// The old way to sort before Go 1.23. It is recommended to use the new slices standard package with Compare.
items := []string{
"gpio10",
"gpio1",
"gpio20",
}
sort.Sort(natural.StringSlice(items))
fmt.Println(strings.Join(items, "\n"))
}
Output: gpio1 gpio10 gpio20
Types ¶
type StringSlice ¶
type StringSlice []string
StringSlice attaches the methods of Interface to []string, sorting in increasing order using natural order.
It is now obsolete, use slices.Sort() along with natural.Compare instead.
func (StringSlice) Len ¶
func (p StringSlice) Len() int
func (StringSlice) Less ¶
func (p StringSlice) Less(i, j int) bool
func (StringSlice) Swap ¶
func (p StringSlice) Swap(i, j int)