- 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
- DevOps:軟件架構師行動指南
- SQL Server 從入門到項目實踐(超值版)
- Google Flutter Mobile Development Quick Start Guide
- 微信公眾平臺與小程序開發:從零搭建整套系統
- R語言經典實例(原書第2版)
- Learning Chef
- C語言程序設計基礎與實驗指導
- Mastering Articulate Storyline
- Unity Virtual Reality Projects
- Python零基礎快樂學習之旅(K12實戰訓練)
- 機器學習與R語言實戰
- Cybersecurity Attacks:Red Team Strategies
- 動手學數據結構與算法
- Java EE企業級應用開發教程(Spring+Spring MVC+MyBatis)
- Web Developer's Reference Guide