通过这个简单的指南,了解如何使用排序包和自定义函数在 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]