下面来介绍Golang两个简单的示例。
1. filter接口
将一个函数作为filter条件去过滤一个数组。
package main
import "fmt"
func compare(filterNum int) bool {
if filterNum > 3 {
return true
}
return false
}
func filterList(sourceList []int, f func(int) bool) []int {
targetList := make([]int, len(sourceList))
for _, num := range sourceList {
if f(num) {
targetList = append(targetList, num)
}
}
return targetList
}
func main() {
testList := []int{1, 2, 3, 4, 5}
target := filterList(testList, compare)
fmt.Println("target list: ", target)
}
2. sort接口
根据定义好的ID顺序,对一个数组进行排序
package main
import (
"fmt"
"sort"
)
type Country struct {
id int
name string
}
// 将一个数组按照某特定的id顺序进行排序
func sortList(targetList []Country, sortIdList []int) {
sort.SliceStable(targetList, func(i, j int) bool {
for _, sortId := range sortIdList {
if targetList[i].id == sortId {
return true
}
if targetList[j].id == sortId {
return false
}
}
return false
})
}
func main() {
countries := []Country{
{id: 1, name: "China"},
{id: 3, name: "France"},
{id: 2, name: "America"},
}
sortIds := []int{3, 2, 1}
sortList(countries, sortIds)
fmt.Println("sorted list: ", countries)
}