Sorting in Go
Go: Sorting
Sorting is a common task in programming, and Go provides a built-in
sort
package that makes it easy to sort slices of various types.
The sort
package provides functions to sort slices of various data types, including strings, integers, and structs, in ascending or descending order.
How to sort a slice of integers in Go
Here's an example of how to use the sort package to sort a slice of integers in ascending order:
package main
import (
"fmt"
"sort"
)
func main() {
nums := []int{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}
// Sort the slice in ascending order
sort.Ints(nums)
fmt.Println(nums) // Output: [1 1 2 3 3 4 5 5 5 6 9]
}
Explainations: In above example, we define a slice of integers nums, and then call the sort.Ints()
function to sort the slice in ascending order. The sorted slice is then printed to the console using the fmt.Println()
function.
How to sort a slice of strings in Go
You can also sort a slice of strings using the sort.Strings()
function:
package main
import (
"fmt"
"sort"
)
func main() {
words := []string{"banana", "apple", "cherry", "date"}
// Sort the slice in alphabetical order
sort.Strings(words)
fmt.Println(words) // Output: [apple banana cherry date]
}
In this example, we define a slice of strings words, and then call the sort.Strings()
function to sort the slice in alphabetical order. The sorted slice is then printed to the console using the fmt.Println()
function.
How to sort a slice of struct in Go
You can sort a slice of structs by defining a custom sort function that compares the fields you want to sort on.
Here's an example:
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func main() {
people := []Person{
{"Alice", 25},
{"Bob", 30},
{"Charlie", 20},
}
// Sort the slice by age
sort.Sort(ByAge(people))
fmt.Println(people) // Output: [{Charlie 20} {Alice 25} {Bob 30}]
}
Explainations: above example, we define a slice of Person structs, and then define a custom ByAge type that implements the sort.Interface interface. The Len(), Swap(), and Less() methods are defined to specify how to compare and sort the slice by age. We then call the sort.Sort() function with a ByAge instance of the people slice, and the slice is sorted by age.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go