Real-World Sorting Examples
Practical Applications of Map Key Sorting
1. User Management System
type User struct {
ID string
Name string
Age int
Salary float64
}
func sortUsersByMultipleCriteria(users map[string]User) {
userIDs := make([]string, 0, len(users))
for id := range users {
userIDs = append(userIDs, id)
}
sort.Slice(userIDs, func(i, j int) bool {
userA := users[userIDs[i]]
userB := users[userIDs[j]]
// Complex sorting logic
if userA.Age != userB.Age {
return userA.Age < userB.Age
}
return userA.Salary > userB.Salary
})
for _, id := range userIDs {
fmt.Printf("User: %+v\n", users[id])
}
}
2. Product Inventory Management
graph TD
A[Inventory Sorting] --> B{Sorting Criteria}
B --> C[Price]
B --> D[Stock Level]
B --> E[Category]
type Product struct {
ID string
Name string
Price float64
Category string
Stock int
}
func sortProductsByPriceAndStock(products map[string]Product) {
productIDs := make([]string, 0, len(products))
for id := range products {
productIDs = append(productIDs, id)
}
sort.Slice(productIDs, func(i, j int) bool {
prodA := products[productIDs[i]]
prodB := products[productIDs[j]]
// Sort by price, then by stock
if prodA.Price != prodB.Price {
return prodA.Price < prodB.Price
}
return prodA.Stock > prodB.Stock
})
}
Sorting Strategies Comparison
Scenario |
Sorting Criteria |
Complexity |
Performance Consideration |
User Management |
Age, Salary |
O(n log n) |
Medium memory overhead |
Product Inventory |
Price, Stock |
O(n log n) |
Minimal additional memory |
Log Analysis |
Timestamp |
O(n log n) |
Depends on data volume |
3. Log Analysis and Timestamp Sorting
type LogEntry struct {
Timestamp time.Time
Message string
Severity string
}
func sortLogsByTimestamp(logs map[string]LogEntry) {
logIDs := make([]string, 0, len(logs))
for id := range logs {
logIDs = append(logIDs, id)
}
sort.Slice(logIDs, func(i, j int) bool {
return logs[logIDs[i]].Timestamp.Before(logs[logIDs[j]].Timestamp)
})
}
- Minimize memory allocations
- Use appropriate sorting methods
- Implement efficient comparison functions
- Consider using specialized data structures
LabEx Best Practices
- Choose the right sorting method
- Validate input data
- Handle edge cases
- Optimize for specific use cases
By understanding these real-world sorting examples, you'll be able to implement efficient and flexible sorting strategies in your Golang applications.