Search⌘ K
AI Features

The sort.Interface Interface

Understand how to implement the sort.Interface in Go by defining Len, Less, and Swap methods for custom slice types. Explore sorting based on embedded struct fields and how sort.Reverse enables reverse ordering. Gain practical experience with sorting slices dynamically.

Definition of sort.Interface

The sort package contains an interface named sort.Interface that allows us to sort slices according to our needs and our data, provided that we implement sort.Interface for the custom data types stored in our slices. The sort package defines the sort.Interface as follows:

Go (1.18.2)
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}

Implementing sort.Interface

...