Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort with a function or method in Go?

Tags:

sorting

go

The sort package provides these functions for sorting the builtin slice types:

  • sort.Ints(a []int)
  • sort.Float64s(a []float64)
  • sort.Strings(a []string)

It also provides these types for converting the builtin slice types to named types with Len(), Less(), Search(), Sort(), and Swap() methods:

  • sort.IntSlice
  • sort.Float64Slice
  • sort.StringSlice

That means I can sort a slice of ints like this...

// Function
slice := []int{5, 4, 3, 2, 1}
sort.Ints(slice) // sort in place

or like this...

// Method
slice := sort.IntSlice{5, 4, 3, 2, 1}
slice.Sort() // also sort in place

Is it preferable to sort with a function or a method? Are there times when one form should be preferred over the other?

like image 568
ryboe Avatar asked May 02 '14 22:05

ryboe


1 Answers

The definition of sort.Ints(x) is literally sort.Sort(sort.IntSlice(x)) so it really doesn't matter. The former is shorter, so I'd use that.

like image 86
Evan Avatar answered Oct 07 '22 15:10

Evan