Golang / GoLang Interfaces and Object Oriented Interview Questions
How do you sort custom types using sort.Interface in Go?
sort.Interface is one of Go's classic interface examples. Any type that implements three methods can be sorted by sort.Sort:
// sort.Interface definition: type Interface interface { Len() int Less(i, j int) bool Swap(i, j int) } // Custom type implementing sort.Interface type Person struct{ Name string; Age int } type ByAge []Person func (b ByAge) Len() int { return len(b) } func (b ByAge) Less(i, j int) bool { return b[i].Age < b[j].Age } func (b ByAge) Swap(i, j int) { b[i], b[j] = b[j], b[i] } people := []Person{ {"Alice", 30}, {"Bob", 25}, {"Carol", 35}, } sort.Sort(ByAge(people)) // convert slice to ByAge to satisfy interface fmt.Println(people) // [{Bob 25} {Alice 30} {Carol 35}] // Modern approach: sort.Slice (no type definition needed) sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name // sort by Name }) // sort.SliceStable â preserves order of equal elements sort.SliceStable(people, func(i, j int) bool { return people[i].Age < people[j].Age }) // Reverse sorting: sort.Reverse wraps any sort.Interface sort.Sort(sort.Reverse(ByAge(people))) // slices.SortFunc (Go 1.21) â generic, type-safe, faster import "slices" slices.SortFunc(people, func(a, b Person) int { return strings.Compare(a.Name, b.Name) // -1, 0, +1 })
The sort.Interface example illustrates how interfaces decouple the sorting algorithm from the data type. sort.Sort knows nothing about Person — it only calls Len, Less, and Swap. This is the Strategy pattern in Go: the algorithm is the same, the comparison strategy is injected via the interface.
More Related questions...