Serve Laurijssen
Serve Laurijssen

Reputation: 9763

How to check if slice of custom struct is sorted?

We can check if a slice of strings is sorted with

var slice = []string { "a", "b }

sort.StringsAreSorted(slice)

But what about when you have struct and you want to know if a slice of that struct is sorted by a certain member?

type Person struct {
  Name string
  LastName string
}

var p = []Person{ {"John", "Smith" }, { "Ben", "Smith" } }

sort.StringsAreSorted(p???)

Upvotes: 3

Views: 1579

Answers (1)

icza
icza

Reputation: 418575

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.

Upvotes: 5

Related Questions