mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-11-01 18:42:34 +00:00
ch7: fix code format
This commit is contained in:
@@ -29,6 +29,7 @@ func (p StringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
|
||||
```go
|
||||
sort.Sort(StringSlice(names))
|
||||
```
|
||||
|
||||
這個轉換得到一個相同長度,容量,和基於names數組的切片值;併且這個切片值的類型有三個排序需要的方法。
|
||||
|
||||
對字符串切片的排序是很常用的需要,所以sort包提供了StringSlice類型,也提供了Strings函數能讓上面這些調用簡化成sort.Strings(names)。
|
||||
@@ -39,8 +40,8 @@ sort.Sort(StringSlice(names))
|
||||
|
||||
下面的變量tracks包好了一個播放列表。(One of the authors apologizes for the other author’s musical tastes.)每個元素都不是Track本身而是指向它的指針。盡管我們在下面的代碼中直接存儲Tracks也可以工作,sort函數會交換很多對元素,所以如果每個元素都是指針會更快而不是全部Track類型,指針是一個機器字碼長度而Track類型可能是八個或更多。
|
||||
|
||||
<u><i>gopl.io/ch7/sorting</i></u>
|
||||
```go
|
||||
//gopl.io/ch7/sorting
|
||||
type Track struct {
|
||||
Title string
|
||||
Artist string
|
||||
@@ -210,6 +211,7 @@ sort.Sort(sort.Reverse(sort.IntSlice(values)))
|
||||
fmt.Println(values) // "[4 3 1 1]"
|
||||
fmt.Println(sort.IntsAreSorted(values)) // "false"
|
||||
```
|
||||
|
||||
爲了使用方便,sort包爲[]int,[]string和[]float64的正常排序提供了特定版本的函數和類型。對於其他類型,例如[]int64或者[]uint,盡管路徑也很簡單,還是依賴我們自己實現。
|
||||
|
||||
**練習 7.8:** 很多圖形界面提供了一個有狀態的多重排序表格插件:主要的排序鍵是最近一次點擊過列頭的列,第二個排序鍵是第二最近點擊過列頭的列,等等。定義一個sort.Interface的實現用在這樣的表格中。比較這個實現方式和重複使用sort.Stable來排序的方式。
|
||||
|
||||
Reference in New Issue
Block a user