samber/lo是基于Go 1.18+泛型的、Lodash風(fēng)格的Go語言庫。Lodash則是一個(gè)一致性、模塊化、高性能的JavaScript實(shí)用工具庫,用于提升開發(fā)者效率,提高原生JavaScript方法的性能,在業(yè)界赫赫有名。
lo項(xiàng)目開始時(shí)作為一個(gè)有新泛型實(shí)現(xiàn)的實(shí)驗(yàn),在某些方面可能看起來像Lodash。作者曾使用go-funk包進(jìn)行編碼,但go-funk使用反射(reflection),因此不是類型安全的。
該項(xiàng)目已經(jīng)在GitHub上積累了6.1k的Star。
- 項(xiàng)目地址:https://github.com/samber/lo
- 開源協(xié)議:MIT License
項(xiàng)目作者Samuel Berthe來自法國(guó)西部城市南特,從事產(chǎn)品型用戶研究。
正如預(yù)期,基準(zhǔn)測(cè)試表明,泛型將比基于反射包的實(shí)現(xiàn)快得多。并且,與純for循環(huán)相比,基準(zhǔn)測(cè)試也顯示出類似的性能提升。
未來,5至10個(gè)助手將與進(jìn)入Go標(biāo)準(zhǔn)庫的助手重疊(在包名稱slices和maps下)。作者認(rèn)為Io庫是合理的,提供了更多有價(jià)值的抽象。
安裝
go get github.com/samber/lo@v1
使用
使用如下命令導(dǎo)入lo:
import ( “github.com/samber/lo” lop “github.com/samber/lo/parallel”)
接著使用如下其中一個(gè)助手:
names := lo.Uniq[string]([]string{“Samuel”, “Marc”, “Samuel”})// []string{“Samuel”, “Marc”}
大多數(shù)時(shí)候,編譯器將可以推斷出類型,這樣你就能夠調(diào)用lo.Uniq([]string{…})。
支持的各類助手(helper)
Slices助手
maps助手
math助手
strings助手
tuples助手
intersection助手
具體展示
Map
操作一種類型的切片,并將它轉(zhuǎn)換為另一種類型的切片:
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函數(shù)在協(xié)程(goroutine)中被調(diào)用,并以相同的順序返回結(jié)果。
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
遍歷一個(gè)集合,并返回predicate函數(shù)返回true的所有元素的一個(gè)數(shù)組。
even := lo.Filter[int]([]int{1, 2, 3, 4}, func(x int, _ int) bool { return x%2 == 0})// []int{2, 4}
Contains
如果一個(gè)元素出現(xiàn)在集合中,則返回true。
present := lo.Contains[int]([]int{0, 1, 2, 3, 4, 5}, 5)// true
更多其他細(xì)節(jié)內(nèi)容請(qǐng)參閱原項(xiàng)目。