Как отсортировать срез в Golang с примерами

Из этого простого руководства вы узнаете, как сортировать фрагменты в Golang с помощью пакета сортировки и пользовательских функций. Включает примеры кода и советы.

Синтаксис

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

Пример

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)
}

Выход

[11 16 21 31 41 51]

#go  #golang 

Как отсортировать срез в Golang с примерами
1.30 GEEK