Agreed! https://pkg.go.dev/sort#Slice is wonderful. (Added a bit after this article was written, I think.)
Agreed! https://pkg.go.dev/sort#Slice is wonderful. (Added a bit after this article was written, I think.)
sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
In Python one might write: people.sort(key=lambda person: person.name)
Or in Rust: people.sort_by_key(|person| person.name); // sort_by is also an option...
I think it's worth calling out exactly what is happening in the Go example:- We create a closure that captures the people slice
- We pass the people slice and the closure to the Slice function
- The Slice function mutates the people slice, and because the closure captured the slice it sees these mutations too
I get why the Go team wrote sort.Slice like that, and it was perhaps the best they could have done with the language features...But I think we're going to have to agree to disagree on how wonderful it is compared to other languages ;).
I’m looking forward to generics improving this too. (e.g. https://github.com/golang/go/issues/47619#issuecomment-91542...)
If I need to reverse the order, it looks easier to do with Go (just reverse the operator) than with Python and Rust way (I guess both have something like an "order" additional parameter).
Rust and Python both feel more elegant but I actually like Go's way.
Sorting by key is a special case (admittedly the most common special case).