Go1.21侯选版增加3个使用泛型的标准库
文章目录
Go1.21侯选版已发布
官方Blog https://go.dev/blog/go1.21rc
部分原文如下:
Standard library additions
- New log/slog package for structured logging.
- New slices package for common operations on slices of any element type. This includes sorting functions that are generally faster and more ergonomic than the sort package.
- New maps package for common operations on maps of any key or element type.
- New cmp package with new utilities for comparing ordered values.
其中 slices, maps, cmp都是应用了泛型的标准库
slices & cmp
cmp主要是提供可比较的类型和函数
|
|
Ordered类型的定义
|
|
slices提供了很多有用的工具函数
|
|
可以看到slices使用到了cmp里的类型和函数
和老的sort库做一个简单的比较,秀一下泛型的存在感
sort库针对不同的类型需要调用不同的函数,后者使用反射,看看sort的编码方式
|
|
slices库的排序编码方式
|
|
maps
提供了对map的一些基本操作
|
|
扩展
在Go里面泛型的使用越来越广泛,这里推荐一些泛型应用的三方库
https://github.com/deckarep/golang-set
使用map实现set的一些功能,特别是集合运算
|
|
https://github.com/samber/lo
lo同样是为slices, maps, channels提供了大量的工具,Lodash风格。
|
|
文章作者 农天狼
上次更新 2023-06-28