Go 1.18发布了!基于 Go 1.18 Generics (泛型) 进行流式处理

xyctruth · 2022-03-14 14:44:29 · 2256 次点击

这种项目一般在泛型发布初期练手时自己写写玩玩,等泛型普及开后,估计官方会有在 golang.com/x 里面加入类似的库。代码中对泛型的声明太冗长了: Elem Result ,可以改成 E R K V T

#1
更多评论

golang.org/x/exp/slices包中已有切片泛型相关函数。

“代码中对泛型的声明太冗长了” ,对于这个问题最初其实很自然也是想用 E,R 等缩写。但是直到我看到 golang.org/x/exp/slices 包中的一些方法:https://github.com/golang/exp/blob/master/slices/sort.go 没使用缩写。

golang.org/x/exp/slices 片段代码

// Sort sorts a slice of any ordered type in ascending order.
func Sort[Elem constraints.Ordered](x []Elem) {
    n := len(x)
    quickSortOrdered(x, 0, n, maxDepth(n))
}

// Sort sorts the slice x in ascending order as determined by the less function.
// This sort is not guaranteed to be stable.
func SortFunc[Elem any](x []Elem, less func(a, b Elem) bool) {
    n := len(x)
    quickSortLessFunc(x, 0, n, maxDepth(n), less)
}
#2

就在刚刚5分钟前,golang.org/x/exp/slices 包更新 slices: consistently use E rather than Elem 😂

#3