package main import ( "fmt" "sort" ) func main() { numbers := []int{10, 5, 3, 8, 2} sort.Slice(numbers, func(i, j int) bool { return numbers[i] < numbers[j] }) fmt.Println(numbers) }
package main import ( "fmt" "sort" ) type People []string func (p People) Len() int { return len(p) } func (p People) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p People) Less(i, j int) bool { return p[i] < p[j] } func main() { names := People{"alice", "bob", "charlie", "david", "ella"} sort.Sort(names) fmt.Println(names) }In the above example, the Len method is defined explicitly as a part of sort.Interface in the People type. It returns the length of the slice of strings. The Len method is used by the Sort function of the sort package to determine the number of elements in the slice. Package: sort