golang學習筆記 排序

2021-10-13 12:46:18 字數 3340 閱讀 9420

這一段時間用到了乙個對一組型別的資料排序,由於golang沒有提供類似c++中set的內建資料結構,這裡需要對乙個slice中的元素進行排序,由淺到深學習golang中的排序。

golang提供了乙個名為sort的包,裡面提供了基礎資料型別的排序:int,float64,string,其他的型別,比如:int32,int64,float32等並沒有實現,但是只要使用者實現了sort包中inte***ce介面的三個函式就可以實現這些型別的排序,sort包中inte***ce的介面:

// a type, typically a collection, that satisfies sort.inte***ce can be

// sorted by the routines in this package. the methods require that the

// elements of the collection be enumerated by an integer index.

type inte***ce inte***ce

以乙個int切片為例:

func

test2()

show

("origin"

, nums...

)// 呼叫sort包中的ints函式排序

sort.

ints

(nums)

show

("inner"

, nums...

)}

結果:

其他的float64,string兩種也是一樣的,呼叫提供的函式即可排序。

我們以int64為例,定義乙個int64的切片,對其排序。整體的思路就是定乙個型別,實現sort中inte***ce介面的三個函式,完成int64型別的排序。

實現介面

type int64slice [

]int64

func

(p int64slice)

len(

)int

func

(p int64slice)

less

(i, j int

)bool

func

(p int64slice)

swap

(i, j int

)func

main()

fmt.

println

("int64排序前:"

, i64)

sort.

sort

(int64slice

(i64)

) fmt.

println

("int64排序後:"

, i64)

}

對於一些自定義的型別來說,也存在需要根據某些字段排序的可能性。我們以學生資訊為例,對自定義的學生資料型別排序。

學生型別如下:

type student struct

我們想通過不同的字段對一組學生排序,比如根據學生的姓名,學生的年齡或者學生的成績排序,分為三部分實施:

定義乙個函式,入參為*student的兩個變數,返回值為bool,通過這個函式可以實現根據學生的多種資訊對學生排序,實現如下:

type by func

(p1, p2 *student)

bool

func

(by by)

sortstudent

(name string

, sutdents [

]student)

// 呼叫sort包中的內建的排序方法

sort.

sort

(ss)

// 自定義的列印排序後的切片內容

ss.show

(name)

}

在學生的排序例項裡,我們要實現sort包的三個介面函式,然後通過將比較的型別的函式傳遞進去,就可以實現學生變數的排序,實現:

// 學生的排序物件

type studentsorter struct

func

(s *studentsorter)

len(

)int

func

(s *studentsorter)

less

(i, j int

)bool

func

(s *studentsorter)

swap

(i, j int

)// 為了列印排序後的資料

func

(s studentsorter)

show

(name string

)}

在根據學生的資訊排序時,要定義by型別的比較函式,根據比較函式方可實現具體的排序,實現:

package main

func

main()

, student

, student

, student,}

name :=

func

(s1, s2 *student)

bool

// 成績公升序

score :=

func

(s1, s2 *student)

bool

// 專門用了倒敘,排序後的年齡應該是降序

age :=

func

(s1, s2 *student)

bool

by(name)

.sortstudent

("按姓名排序"

, ss)

by(score)

.sortstudent

("按成績排序"

, ss)

by(age)

.sortstudent

("按年齡排序"

, ss)

}

結果:

Golang學習筆記

如果乙個method的receiver是 t,你可以在乙個t型別的例項變數v上面呼叫這個method,而不需要 v去呼叫這個method 即不需要 v method 如果乙個method的receiver是t,你可以在乙個 t型別的變數p上呼叫這個method,而不需要 p去呼叫這個method。i...

golang學習筆記

與c語法不同之處 1.引數列表中各個引數型別相同時可以只寫出最後乙個,如 add x,y int int 2.型別在引數名 變數 函式 後面 3.函式的左大括號要跟函式名同一行,否則編譯不過 4.函式定義要先寫關鍵字func在函式開頭 函式外的每個語句都要以func var等等關鍵字開頭 5.在包或...

Golang學習筆記

package main import fmt func main break default func inte ce select case defer gomap struct chan else goto package switch const fallthrough ifrange ty...