基于Go 1.18+泛型、Lodash风格的Go语言库,支持切片和map等助手

samber/lo是基于Go 1.18+泛型的、Lodash风格的Go语言库Lodash则是一个一致性、模块化、高性能的JavaScript实用工具库,用于提升开发者效率,提高原生JavaScript方法的性能,在业界赫赫有名。

lo项目开始时作为一个有新泛型实现的实验,在某些方面可能看起来像Lodash。作者曾使用go-funk包进行编码,但go-funk使用反射(reflection),因此不是类型安全的。

该项目已经在GitHub上积累了6.1k的Star。

基于Go 1.18+泛型、Lodash风格的Go语言库,支持切片和map等助手

  • 项目地址:https://github.com/samber/lo
  • 开源协议:MIT License

项目作者Samuel Berthe来自法国西部城市南特,从事产品型用户研究。

基于Go 1.18+泛型、Lodash风格的Go语言库,支持切片和map等助手

正如预期,基准测试表明,泛型将比基于反射包的实现快得多。并且,与纯for循环相比,基准测试也显示出类似的性能提升。

未来,5至10个助手将与进入Go标准库的助手重叠(在包名称slices和maps下)。作者认为Io库是合理的,提供了更多有价值的抽象。

安装

go get github.com/samber/lo@v1

使用

使用如下命令导入lo

import (
    "github.com/samber/lo"
    lop "github.com/samber/lo/parallel"
)

接着使用如下其中一个助手:

names := lo.Uniq[string]([]string{"Samuel", "Marc", "Samuel"})
// []string{"Samuel", "Marc"}

大多数时候,编译器将可以推断出类型,这样你就能够调用lo.Uniq([]string{...})

支持的各类助手(helper)

Slices助手

基于Go 1.18+泛型、Lodash风格的Go语言库,支持切片和map等助手

maps助手

基于Go 1.18+泛型、Lodash风格的Go语言库,支持切片和map等助手

math助手

基于Go 1.18+泛型、Lodash风格的Go语言库,支持切片和map等助手

strings助手

基于Go 1.18+泛型、Lodash风格的Go语言库,支持切片和map等助手

tuples助手

基于Go 1.18+泛型、Lodash风格的Go语言库,支持切片和map等助手

intersection助手

基于Go 1.18+泛型、Lodash风格的Go语言库,支持切片和map等助手

具体展示

Map

操作一种类型的切片,并将它转换为另一种类型的切片:

import "github.com/samber/lo"

lo.Map[int64, string]([]int64{1, 2, 3, 4}, func(x int64, _ int) string {
    return strconv.FormatInt(x, 10)
})
// []string{"1", "2", "3", "4"}

并行处理:像lo.Map()一样。但mapper函数在协程(goroutine)中被调用,并以相同的顺序返回结果。

import lop "github.com/samber/lo/parallel"

lop.Map[int64, string]([]int64{1, 2, 3, 4}, func(x int64, _ int) string {
    return strconv.FormatInt(x, 10)
})
// []string{"1", "2", "3", "4"}

Filter

遍历一个集合,并返回predicate函数返回true的所有元素的一个数组。

even := lo.Filter[int]([]int{1, 2, 3, 4}, func(x int, _ int) bool {
    return x%2 == 0
})
// []int{2, 4}

Contains

如果一个元素出现在集合中,则返回true

present := lo.Contains[int]([]int{0, 1, 2, 3, 4, 5}, 5)
// true

更多其他细节内容请参阅原项目。

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章