Golang: Sorting a slice of basic types and custom types

Claire Lee
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.

Golang: sorting summary card

Sorting a Slice of basic types

Use built-in function

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

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.

--

--

Claire Lee
Claire Lee

No responses yet