ryboe
ryboe

Reputation: 2842

Sort with a function or method in Go?

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

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

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?

Upvotes: 6

Views: 910

Answers (1)

Evan
Evan

Reputation: 6545

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.

Upvotes: 9

Related Questions