在Go语言中slice比数组更强大、灵活、方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储相似类型的元素,你不允许在同一个slice中存储不同类型的元素。
在Go语言中,你可以在 Slice() 函数的帮助下对一个slice进行排序。这个函数对指定的片断进行排序,并给出了所提供的less函数。这个函数的结果是不稳定的。因此,为了获得稳定的排序,你可以使用SliceStable。如果指定的接口不是slice类型,这个函数就会慌乱。它被定义在sort包下,因此,你必须在你的程序中导入sort包以访问Slice函数。
语法
func Slice(a_slice interface{}, less func(p, q int) bool)
例子
// Go program to illustrate
// how to sort a slice
package main
import (
"fmt"
"sort"
)
// Main function
func main() {
// Creating and initializing
// a structure
Author := []struct {
a_name string
a_article int
a_id int
}{
{"Mina", 304, 1098},
{"Cina", 634, 102},
{"Tina", 104, 105},
{"Rina", 10, 108},
{"Sina", 234, 103},
{"Vina", 237, 106},
{"Rohit", 56, 107},
{"Mohit", 300, 104},
{"Riya", 4, 101},
{"Sohit", 20, 110},
}
// Sorting Author by their name
// Using Slice() function
sort.Slice(Author, func(p, q int) bool {
return Author[p].a_name < Author[q].a_name })
fmt.Println("Sort Author according to their names:")
fmt.Println(Author)
// Sorting Author by their
// total number of articles
// Using Slice() function
sort.Slice(Author, func(p, q int) bool {
return Author[p].a_article < Author[q].a_article })
fmt.Println()
fmt.Println("Sort Author according to their"+
" total number of articles:")
fmt.Println(Author)
// Sorting Author by their ids
// Using Slice() function
sort.Slice(Author, func(p, q int) bool {
return Author[p].a_id < Author[q].a_id })
fmt.Println()
fmt.Println("Sort Author according to the their Ids:")
fmt.Println(Author)
}
输出
Sort Author according to their names:
[{Cina 634 102} {Mina 304 1098} {Mohit 300 104} {Rina 10 108} {Riya 4 101} {Rohit 56 107} {Sina 234 103} {Sohit 20 110} {Tina 104 105} {Vina 237 106}]
Sort Author according to their total number of articles:
[{Riya 4 101} {Rina 10 108} {Sohit 20 110} {Rohit 56 107} {Tina 104 105} {Sina 234 103} {Vina 237 106} {Mohit 300 104} {Mina 304 1098} {Cina 634 102}]
Sort Author according to the their Ids:
[{Riya 4 101} {Cina 634 102} {Sina 234 103} {Mohit 300 104} {Tina 104 105} {Vina 237 106} {Rohit 56 107} {Rina 10 108} {Sohit 20 110} {Mina 304 1098}]