Custom Sorting
Implementing the sort.Interface
Go provides a powerful way to create custom sorting by implementing the sort.Interface
:
type Interface interface {
Len() int // Length of the collection
Less(i, j int) bool // Comparison logic
Swap(i, j int) // Swapping elements
}
Custom Sorting Workflow
graph TD
A[Custom Type] --> B[Implement sort.Interface]
B --> C[Len() Method]
B --> D[Less() Method]
B --> E[Swap() Method]
C,D,E --> F[sort.Sort() Function]
Practical Example: Sorting Custom Structs
package main
import (
"fmt"
"sort"
)
type Product struct {
Name string
Price float64
}
type ByPrice []Product
func (a ByPrice) Len() int { return len(a) }
func (a ByPrice) Less(i, j int) bool { return a[i].Price < a[j].Price }
func (a ByPrice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func main() {
products := []Product{
{"Laptop", 1200.50},
{"Smartphone", 800.25},
{"Tablet", 500.75},
}
sort.Sort(ByPrice(products))
fmt.Println("Sorted by price:", products)
}
Advanced Sorting Techniques
Technique |
Description |
Use Case |
Multiple Criteria Sorting |
Sort by multiple fields |
Complex sorting logic |
Reverse Sorting |
Invert default sorting |
Descending order |
Stable Sorting |
Preserve original order |
Maintaining relative positions |
Reverse Sorting Example
package main
import (
"fmt"
"sort"
)
func main() {
numbers := []int{5, 2, 8, 1, 9}
sort.Sort(sort.Reverse(sort.IntSlice(numbers)))
fmt.Println("Reversed sort:", numbers)
}
- Custom sorting provides maximum flexibility
- Implement methods efficiently
- Use
sort.Slice()
for simple cases
- Implement
sort.Interface
for complex sorting logic
Multi-Criteria Sorting
package main
import (
"fmt"
"sort"
)
type Student struct {
Name string
Grade int
Age int
}
type ByGradeThenAge []Student
func (a ByGradeThenAge) Len() int { return len(a) }
func (a ByGradeThenAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByGradeThenAge) Less(i, j int) bool {
if a[i].Grade == a[j].Grade {
return a[i].Age < a[j].Age
}
return a[i].Grade > a[j].Grade
}
func main() {
students := []Student{
{"Alice", 90, 18},
{"Bob", 85, 17},
{"Charlie", 90, 16},
}
sort.Sort(ByGradeThenAge(students))
fmt.Println("Sorted students:", students)
}
At LabEx, we encourage developers to master these custom sorting techniques to write more flexible and powerful Go applications.