## 4.11\. Sorting
接口(interfaces)提供了一個簡單形式的多態(polymorphism). 他們把對象的定義和 如何實現的分開處理,允許相同的接口可以有不能的實現方法。
參考這個簡單的排序算法(sort algorithm)"progs/sort.go"
```
13 func Sort(data Interface) {
14 for i := 1; i < data.Len(); i++ {
15 for j := i; j > 0 && data.Less(j, j-1); j-- {
16 data.Swap(j, j-1)
17 }
18 }
19 }
```
我們要封裝這個排序(sort)的接口(interface)僅需要三個方法。
```
07 type Interface interface {
08 Len() int
09 Less(i, j int) bool
10 Swap(i, j int)
11 }
```
我們可以用任何類型的"Sort"去實現"Len", "Less" 和 "Swap". 這個"sort"包里面 包含一些方法(methods). 下面是整型數組的代碼:
```
33 type IntArray []int
35 func (p IntArray) Len() int { return len(p) }
36 func (p IntArray) Less(i, j int) bool { return p[i] < p[j] }
37 func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
```
你看到的是一個沒有任何類型的"結構體"(non-struct type). 在你的包里面你可以定義 任何你想定義的類型.
現在用"progs/sortmain.go"程序進行測試,用"sort"包里面的排序函數進行排序。
```
12 func ints() {
13 data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586}
14 a := sort.IntArray(data)
15 sort.Sort(a)
16 if !sort.IsSorted(a) {
17 panic("fail")
18 }
19 }
```
如果我們為sort提供一個新類型,我們就需要為這個類型實現三個方法,如下:
```
30 type day struct {
31 num int
32 shortName string
33 longName string
34 }
36 type dayArray struct {
37 data []*day
38 }
40 func (p *dayArray) Len() int { return len(p.data) }
41 func (p *dayArray) Less(i, j int) bool { return p.data[i].num < p.data[j].num }
42 func (p *dayArray) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i] }
```
- 1. 關于本文
- 2. Go語言簡介
- 3. 安裝go環境
- 3.1. 簡介
- 3.2. 安裝C語言工具
- 3.3. 安裝Mercurial
- 3.4. 獲取代碼
- 3.5. 安裝Go
- 3.6. 編寫程序
- 3.7. 進一步學習
- 3.8. 更新go到新版本
- 3.9. 社區資源
- 3.10. 環境變量
- 4. Go語言入門
- 4.1. 簡介
- 4.2. Hello,世界
- 4.3. 分號(Semicolons)
- 4.4. 編譯
- 4.5. Echo
- 4.6. 類型簡介
- 4.7. 申請內存
- 4.8. 常量
- 4.9. I/O包
- 4.10. Rotting cats
- 4.11. Sorting
- 4.12. 打印輸出
- 4.13. 生成素數
- 4.14. Multiplexing
- 5. Effective Go
- 5.1. 簡介
- 5.2. 格式化
- 5.3. 注釋
- 5.4. 命名
- 5.5. 分號
- 5.6. 控制流
- 5.7. 函數
- 5.8. 數據
- 5.9. 初始化
- 5.10. 方法
- 5.11. 接口和其他類型
- 5.12. 內置
- 5.13. 并發
- 5.14. 錯誤處理
- 5.15. Web服務器
- 6. 如何編寫Go程序
- 6.1. 簡介
- 6.2. 社區資源
- 6.3. 新建一個包
- 6.4. 測試
- 6.5. 一個帶測試的演示包
- 7. Codelab: 編寫Web程序
- 7.1. 簡介
- 7.2. 開始
- 7.3. 數據結構
- 7.4. 使用http包
- 7.5. 基于http提供wiki頁面
- 7.6. 編輯頁面
- 7.7. template包
- 7.8. 處理不存在的頁面
- 7.9. 儲存頁面
- 7.10. 錯誤處理
- 7.11. 模板緩存
- 7.12. 驗證
- 7.13. 函數文本和閉包
- 7.14. 試試!
- 7.15. 其他任務
- 8. 針對C++程序員指南
- 8.1. 概念差異
- 8.2. 語法
- 8.3. 常量
- 8.4. Slices(切片)
- 8.5. 構造值對象
- 8.6. Interfaces(接口)
- 8.7. Goroutines
- 8.8. Channels(管道)
- 9. 內存模型
- 9.1. 簡介
- 9.2. Happens Before
- 9.3. 同步(Synchronization)
- 9.4. 錯誤的同步方式
- 10. 附錄
- 10.1. 命令行工具
- 10.2. 視頻和講座
- 10.3. Release History
- 10.4. Go Roadmap
- 10.5. 相關資源