How to Sort Slice in Golang with Examples

Learn how to sort slice in Golang using the sort package and custom functions with this easy guide. Includes code examples and tips.

Syntax

func Slice(a_slice interface{}, less func(p, q int) bool)

Example

package main

import (
  "fmt"
  "sort"
)

func main() {
  // Define a slice of integers.
  nums := []int{51, 21, 16, 31, 11, 41}

  // Use sort.Slice() to sort the slice.
  sort.Slice(nums, func(i, j int) bool {
 
  // This function determines the sort order.
  // It should return true if the element
  // at index i should be sorted before the element at index j.
  return nums[i] < nums[j]
 })

  // Print the sorted slice.
  fmt.Println(nums)
}

Output

[11 16 21 31 41 51]

#go #golang 

How to Sort Slice in Golang with Examples
1.30 GEEK