How to Sort Slice of Structs in Go: Simple Guide
In Go, you can sort a slice of structs using
sort.Slice by providing a custom comparison function that defines the sorting order. This function compares two elements and returns true if the first should come before the second. This approach is simple and flexible for sorting by any struct field.Syntax
Use sort.Slice(slice, func(i, j int) bool { ... }) where:
sliceis your slice of structs.- The function compares elements at index
iandj. - Return
trueif element atishould come before element atj.
go
sort.Slice(slice, func(i, j int) bool { return slice[i].Field < slice[j].Field })
Example
This example sorts a slice of Person structs by their Age field in ascending order.
go
package main import ( "fmt" "sort" ) type Person struct { Name string Age int } func main() { people := []Person{ {"Alice", 30}, {"Bob", 25}, {"Charlie", 35}, } sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age }) for _, p := range people { fmt.Printf("%s: %d\n", p.Name, p.Age) } }
Output
Bob: 25
Alice: 30
Charlie: 35
Common Pitfalls
Common mistakes include:
- Not providing a correct comparison function, which can cause incorrect sorting.
- Using
<when you want descending order (should use>instead). - Modifying the slice while sorting, which can cause unexpected behavior.
go
package main import ( "fmt" "sort" ) type Item struct { Value int } func main() { items := []Item{{3}, {1}, {2}} // Wrong: returns false always, no sorting sort.Slice(items, func(i, j int) bool { return false }) fmt.Println("Wrong sort result:", items) // Correct: ascending order sort.Slice(items, func(i, j int) bool { return items[i].Value < items[j].Value }) fmt.Println("Correct sort result:", items) }
Output
Wrong sort result: [{3} {1} {2}]
Correct sort result: [{1} {2} {3}]
Quick Reference
| Step | Description |
|---|---|
| 1 | Import "sort" package |
| 2 | Define your slice of structs |
| 3 | Call sort.Slice with your slice and a comparison function |
| 4 | Comparison function returns true if element i should come before j |
| 5 | Run your program to see sorted slice |
Key Takeaways
Use sort.Slice with a custom comparison function to sort slices of structs.
The comparison function should return true if the first element should come before the second.
Remember to import the sort package before sorting.
Be careful to define the comparison logic correctly for ascending or descending order.
Avoid modifying the slice while sorting to prevent unexpected results.