If your type implements sort.Interface
, simply use the sort.IsSorted()
function.
If not, you may use sort.SliceIsSorted()
, passing a less()
function which decides / specifies the order(ing):
sortedByName := sort.SliceIsSorted(p, func(i, j int) bool {
return p[i].Name < p[j].Name
})
fmt.Println("Sorted by name:", sortedByName)
sortedByLastName := sort.SliceIsSorted(p, func(i, j int) bool {
return p[i].LastName < p[j].LastName
})
fmt.Println("Sorted by last name:", sortedByLastName)
This will output (try it on the Go Playground):
Sorted by name: false
Sorted by last name: true
If you look into the implementation of these functions, they use a simple loop to iterate over the elements and tell if the ones being next to each other does not violate the ordering (less()
function). You may just as easily use a for loop too.