4 ms·
Before generics, Go sorting usually looked like this: type ByValue []int func (a ByValue) Len() int { return len(a) } func (a ByValue) Swap(i, j int
by tamnd 1y ago
Before generics, Go sorting usually looked like this:
type ByValue []int
func (a ByValue) Len() int { return len(a) }
func (a ByValue) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByValue) Less(i, j int) bool { return a[i] < a[j] }
sort.Sort(ByValue(a))
It worked fine but felt a bit awkward for small programs. After Go 1.18, you can do it directly with generics:
s := []int{3, 1, 4, 1, 5, 9}
slices.Sort(s)
Much simpler and expressive, yet still type safe. I really like how Go kept it minimal without adding too many abstractions.
- kragen 1y agoYup. You might want to indent your code four spaces. Compare how it's done in ML, which has had generics for almost 50 years: https://ocaml.org/cookbook/sorting-lists-and-arrays/stdlib https://ocaml.org/cookbook/sorting-lists-and-arrays/stdlib https://ocaml.org/manual/5.4/api/List.html#1_Sorting https://ocaml.org/manual/5.4/api/List.html#1_Sorting