# 从插入排序来理解 Go 的接口

func insertionSort(data []int) {
lo, hi := 0, len(data) - 1
for i := lo + 1; i  lo && data[j] < data[j-1]; j-- {
data[j], data[j-1] = data[j-1], data[j]
}
}
}

package main

import (
"fmt"
)

func main()  {
nums := []int{2, 3, 4, 1, 7, 9, 10, 21, 17}
insertionSort(nums)
fmt.Println(nums)
}

[1 2 3 4 7 9 10 17 21]

### 问题

func insertionSortUint32(data []uint32) {
lo, hi := 0, len(data) - 1
for i := lo + 1; i  lo && data[j] < data[j-1]; j-- {
data[j], data[j-1] = data[j-1], data[j]
}
}
}

func insertionSortFloat32(data []float32) {
lo, hi := 0, len(data) - 1
for i := lo + 1; i  lo && data[j] < data[j-1]; j-- {
data[j], data[j-1] = data[j-1], data[j]
}
}
}

### 解决

type Data interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}

func insertionSort(data Data) {
lo, hi := 0, data.Len() - 1
for i := lo + 1; i  lo && data.Less(j, j-1); j-- {
data.Swap(j, j-1)
}
}
}

package main

import (
"fmt"
)

type Uint32Slice []uint32

func (u Uint32Slice) Len() int {return len(u)}
func (u Uint32Slice) Less(i, j int) bool {return u[i] < u[j]}
func (u Uint32Slice) Swap(i, j int) {u[i], u[j] = u[j], u[i]}

type Float32Slice []float32

func (u Float32Slice) Len() int {return len(u)}
func (u Float32Slice) Less(i, j int) bool {return u[i] < u[j]}
func (u Float32Slice) Swap(i, j int) {u[i], u[j] = u[j], u[i]}

func main()  {
nums := Uint32Slice{2, 3, 4, 1, 7, 9, 10, 21, 17}
insertionSort(nums)
fmt.Println(nums)

float32Nums := Float32Slice{2, 3, 4, 1, 7, 9, 10, 21, 17}
insertionSort(float32Nums)
fmt.Println(float32Nums)
}

[1 2 3 4 7 9 10 21 17]
[1 2 3 4 7 9 10 21 17]