Golang: Sorting a slice of basic types and custom types
2 min readAug 17, 2022
For Sorting a slice of basic types, int, float64 and string, we can use build-in functions, sort.Ints, sort.Float64s and sort.Strings to get a sorted slice in ascending order. When it comes to custom types, there are two ways to sort, sort.Slice or sort.Sort. Use sort.Sort function will need to create a corresponding custom type to implement sort.Interface ahead.
Sorting a Slice of basic types
Use built-in function
- int slices: sort.Ints
- float64 slices: sort.Float64s
- string slices: sort.Strings
Sorting a Slice of custom types
Use function sort.Slice
- sort a slice by a specified field
- use the provided less function to decide the sorted order.
func Slice(x interface{}, less func(i, j int) bool)
- no need to create custom type for the slice
Use function sort.Sort
- custom sorting by implementing sort.Interface
type Interface interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
- need to create a custom type for the slice to implement sort.Interface
You can reach the whole source code here.