0
0
GoHow-ToBeginner · 3 min read

How to Use sort.Interface in Go for Custom Sorting

In Go, sort.Interface is used to define custom sorting by implementing three methods: Len(), Less(i, j int), and Swap(i, j int). You create a type that implements these methods and then call sort.Sort(yourType) to sort your data.
📐

Syntax

To use sort.Interface, define a type that implements these three methods:

  • Len() int: returns the number of elements.
  • Less(i, j int) bool: returns true if element at index i should come before element at index j.
  • Swap(i, j int): swaps elements at indexes i and j.

Then call sort.Sort(yourType) to sort the collection.

go
type YourType []Element

func (y YourType) Len() int {
    return len(y)
}

func (y YourType) Less(i, j int) bool {
    // define comparison logic
    return y[i] < y[j]
}

func (y YourType) Swap(i, j int) {
    y[i], y[j] = y[j], y[i]
}

// Then sort with:
sort.Sort(YourType(yourSlice))
💻

Example

This example shows how to sort a slice of strings in reverse alphabetical order by implementing sort.Interface.

go
package main

import (
    "fmt"
    "sort"
)

type ReverseStrings []string

func (r ReverseStrings) Len() int {
    return len(r)
}

func (r ReverseStrings) Less(i, j int) bool {
    return r[i] > r[j] // reverse order
}

func (r ReverseStrings) Swap(i, j int) {
    r[i], r[j] = r[j], r[i]
}

func main() {
    fruits := []string{"apple", "banana", "cherry", "date"}
    sort.Sort(ReverseStrings(fruits))
    fmt.Println(fruits)
}
Output
[date cherry banana apple]
⚠️

Common Pitfalls

Common mistakes when using sort.Interface include:

  • Not implementing all three methods (Len, Less, Swap).
  • Incorrect logic in Less causing unexpected order.
  • Using a pointer receiver when a value receiver is expected or vice versa.
  • Modifying the slice outside of Swap during sorting.

Always test your Less logic carefully to ensure correct sorting.

go
/* Wrong: Missing Swap method

func (r ReverseStrings) Len() int {
    return len(r)
}

func (r ReverseStrings) Less(i, j int) bool {
    return r[i] > r[j]
}

// sort.Sort will fail because Swap is missing
*/

/* Correct: Implement all methods

func (r ReverseStrings) Swap(i, j int) {
    r[i], r[j] = r[j], r[i]
}
*/
📊

Quick Reference

MethodPurpose
Len() intReturns the number of elements to sort
Less(i, j int) boolReturns true if element i should come before element j
Swap(i, j int)Swaps elements at indexes i and j

Key Takeaways

Implement Len, Less, and Swap methods to satisfy sort.Interface for custom sorting.
Use sort.Sort(yourType) to sort your data after implementing the interface.
Ensure Less method logic correctly defines the desired order.
All three methods must be implemented to avoid runtime errors.
Use value receivers for methods unless your type requires pointer receivers.