官术网_书友最值得收藏!

  • Go Systems Programming
  • Mihalis Tsoukalos
  • 357字
  • 2021-07-02 18:08:06

The sort.Slice() function

This section will illustrate the use of the sort.Slice() function that first came with Go version 1.8. The use of the function will be illustrated in sortSlice.go, which will be presented in three parts.

The first part is the expected preamble of the program and the definition of a new structure type, given as follows:

package main 
 
import ( 
   "fmt" 
   "sort" 
) 
 
type aStructure struct { 
   person string 
   height int 
   weight int 
} 

As you might expect, you have to import the sort package to be able to use its Slice() function.

The second part contains the definition of a slice, which has four elements:

func main() { 
 
   mySlice := make([]aStructure, 0) 
   a := aStructure{"Mihalis", 180, 90}
mySlice = append(mySlice, a) a = aStructure{"Dimitris", 180, 95} mySlice = append(mySlice, a) a = aStructure{"Marietta", 155, 45} mySlice = append(mySlice, a) a = aStructure{"Bill", 134, 40} mySlice = append(mySlice, a)

Therefore, in the first part, you declared a slice of structure that will be sorted in two ways in the rest of the program, which contains the following code:

   fmt.Println("0:", mySlice) 
   sort.Slice(mySlice, func(i, j int) bool { 
         return mySlice[i].weight <mySlice[j].weight 
   }) 
   fmt.Println("<:", mySlice) 
   sort.Slice(mySlice, func(i, j int) bool { 
         return mySlice[i].weight >mySlice[j].weight 
   }) 
   fmt.Println(">:", mySlice) 
} 

This code contains all the magic: you only have to define the way you want to sort your slice and the rest is done by Go. The sort.Slice() function takes the anonymous sorting function as one of its arguments; the other argument is the name of the slice variable you want to sort. Note that the sorted slice is saved in the slice variable.

Executing sortSlice.go will generate the following output:

$ go run sortSlice.go
0: [{Mihalis 180 90} {Dimitris 180 95} {Marietta 155 45} {Bill 134 40}]
<: [{Bill 134 40} {Marietta 155 45} {Mihalis 180 90} {Dimitris 180 95}]
>: [{Dimitris 180 95} {Mihalis 180 90} {Marietta 155 45} {Bill 134 40}]

As you can see, you can easily sort in ascending or descending order by just changing a single character in the Go code!

Also, if your Go version does not support sort.Slice(), you will get an error message similar to the following:

$ go version
go version go1.3.3 linux/amd64
$ go run sortSlice.go
# command-line-arguments
./sortSlice.go:27: undefined: sort.Slice
./sortSlice.go:31: undefined: sort.Slice
主站蜘蛛池模板: 景德镇市| 红原县| 江孜县| 汾阳市| 怀安县| 福海县| 太康县| 无极县| 西华县| 资兴市| 大连市| 维西| 松江区| 色达县| 祥云县| 娄底市| 新干县| 绥化市| 万荣县| 岐山县| 东辽县| 永和县| 金华市| 玛纳斯县| 灵山县| 綦江县| 吴江市| 资兴市| 成安县| 广安市| 上饶市| 青海省| 绥德县| 恭城| 乐陵市| 河池市| 化德县| 壤塘县| 唐山市| 秦安县| 长汀县|