I'm writing a sort function for a specific type. When writing the receiver "Less()" I call another function that might return an error. As Less() itself returns a bool what is the right way to handle this scenario? I don't want to panic, but I'd like to indicate that the attempt at sorting has failed, such that the function calling sort.Sort() can decide what to do with the error. However, sort.Sort() does not seem to return an error either so I'm guessing there is another way to go about this.
func (t MyType) Less(i, j int) bool {
retval, err := myOtherFunc(t[i])
// How do I handle err?
}
You can't; the closest solution would be to use sort.Slice
instead, with a closure you can use to trap the error(s) in the outer scope:
errs := make([]error)
sort.Slice(mySlice, func(i, j int) bool {
retval, err := myOtherFunc(mySlice[i])
if err != nil {
errs = append(errs, err)
}
return retval
})
if len(errs) > 0 {
// do something about errors
}
This won't stop sorting at the first error (you can't), but it at least lets you collect them. The sort
package is meant for typical sorting heuristics like alphabetical, numeric, or alpha/numeric on a struct field or the like; not for more complex processes with the possibility of failure.