亚洲区国产区激情区无码区,国产成人mv视频在线观看,国产A毛片AAAAAA,亚洲精品国产首次亮相在线

Golang 菜鳥教程

Golang 控制語(yǔ)句

Golang 函數(shù) & 方法

Golang 結(jié)構(gòu)體

Golang 切片 & 數(shù)組

Golang 字符串(String)

Golang 指針

Golang 接口

Golang 并發(fā)

Golang 異常(Error)

Golang 其他雜項(xiàng)

Go 語(yǔ)言排序(Sort)

Go具有Sort包,可用于對(duì)內(nèi)置以及用戶定義的數(shù)據(jù)類型進(jìn)行排序。

sort包具有不同的方法來對(duì)不同的數(shù)據(jù)類型進(jìn)行排序,例如Ints(),F(xiàn)loat64s(),Strings()等。

我們可以使用AreSorted()方法(例如Float64sAreSorted(),IntsAreSorted()等)來檢查值是否排序。

Go 排序示例

package main
import (
	"sort"
	"fmt"
)
func main() {

	intValue := []int{10, 20, 5, 8}
	sort.Ints(intValue)
	fmt.Println("Ints:   ", intValue)

	floatValue := []float64{10.5, 20.5, 5.5, 8.5}
	sort.Float64s(floatValue)
	fmt.Println("floatValue:   ", floatValue)

	stringValue := []string{"Raj", "Mohan", "Roy"}
	sort.Strings(stringValue)
	fmt.Println("Strings:", stringValue)

	str := sort.Float64sAreSorted(floatValue)
	fmt.Println("Sorted: ", s

輸出:

Ints:    [5 8 10 20]
floatValue:    [5.5 8.5 10.5 20.5]
Strings: [Mohan Raj Roy]
Sorted:  true

假設(shè)我們想根據(jù)字符串的長(zhǎng)度對(duì)字符串?dāng)?shù)組進(jìn)行排序,我們還可以實(shí)現(xiàn)自己的排序模式。為此,我們必須實(shí)現(xiàn)在排序接口中定義的自己的Less,Len和Swap方法。

然后,我們必須將數(shù)組轉(zhuǎn)換為實(shí)現(xiàn)的類型。

package main
import "sort"
import "fmt"

type  OrderByLengthDesc []string
func (s OrderByLengthDesc) Len() int {
	return len(s)
}
func (str OrderByLengthDesc) Swap(i, j int) {
	str[i], str[j] = str[j], str[i]
}
func (s OrderByLengthDesc) Less(i, j int) bool {
	return len(s[i]) > len(s[j])
}
func main() {
	city := []string{"New York", "London","Washington","Delhi"}
	sort.Sort(OrderByLengthDesc(city))
	fmt.Println(city)
}

輸出:

[Washington New York London Delhi]