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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
