使用 samber/lo 为 Golang 提供函数式编程辅助 — 500+ 类型安全的泛型函数,涵盖 slice、map、channel、string、数学、元组以及并发...
Persona: You are a Go engineer who prefers declarative collection transforms over manual loops. You reach for lo to eliminate boilerplate, but you know when the stdlib is enough and when to upgrade to lop, lom, or loi.
Lodash-inspired, generics-first utility library with 500+ type-safe helpers for slices, maps, strings, math, channels, tuples, and concurrency. Zero external dependencies. Immutable by default.
Official Resources:
This skill is not exhaustive. Please refer to library documentation and code examples for more information. For Go package docs, symbols, versions, importers, and known vulnerabilities, → See samber/cc-skills-golang@golang-pkg-go-dev skill ( godig) — prefer it over Context7 for Go package facts. To navigate this library's usage in your own code (definitions, call sites, diagnostics), → See samber/cc-skills-golang@golang-gopls skill ( gopls). Context7 remains a fallback for docs not indexed on pkg.go.dev.
Go's stdlib slices and maps packages cover ~10 basic helpers (sort, contains, keys). Everything else — Map, Filter, Reduce, GroupBy, Chunk, Flatten, Zip — requires manual for-loops. lo fills this gap:
interface{} casts, no reflection, compile-time checking, no interface boxing overheadlo, upgrade to lop/ lom/ loi only when profiling demands itErr suffixes ( MapErr, FilterErr, ReduceErr) that stop on first errorbash
go get github.com/samber/lo
PackageImportAliasGo versionCore (immutable)github.com/samber/lo``lo1.18+Parallelgithub.com/samber/lo/parallel``lop1.18+Mutablegithub.com/samber/lo/mutable``lom1.18+Iteratorgithub.com/samber/lo/it``loi1.23+SIMD (experimental)github.com/samber/lo/exp/simd—1.25+ (amd64 only)
Start with lo. Move to other packages only when profiling shows a bottleneck or when lazy evaluation is explicitly needed.
PackageUse whenTrade-offloDefault for all transformsAllocates new collections (safe, predictable)lopCPU-bound work on large datasets (1000+ items)Goroutine overhead; not for I/O or small sliceslomHot path confirmed by pprof -alloc_objectsMutates input — caller must understand side effectsloiLarge datasets with chained transforms (Go 1.23+)Lazy evaluation saves memory but adds iterator complexitysimdNumeric bulk ops after benchmarking (experimental)Unstable API, may break between versions
Key rules:
lop is for CPU parallelism, not I/O concurrency — for I/O fan-out, use errgroup insteadlom breaks immutability — only use when allocation pressure is measured, never assumedloi eliminates intermediate allocations in chains like Map → Filter → Take by evaluating lazilysamber/cc-skills-golang@golang-samber-ro skill + samber/ro packageFor detailed package comparison and decision flowchart, see Package Guide.
go
// ✓ lo — declarative, type-safe
names := lo.Map(users, func(u User, _ int) string {
return u.Name
})
// ✗ Manual — boilerplate, error-prone
names := make([]string, 0, len(users))
for _, u := range users {
names = append(names, u.Name)
}
go
total := lo.Reduce(
lo.Filter(orders, func(o Order, _ int) bool {
return o.Status == "paid"
}),
func(sum float64, o Order, _ int) float64 {
return sum + o.Amount
},
0,
)
go
byStatus := lo.GroupBy(tasks, func(t Task, _ int) string {
return t.Status
})
// map[string][]Task{"open": [...], "closed": [...]}
go
results, err := lo.MapErr(urls, func(url string, _ int) (Response, error) {
return http.Get(url)
})
MistakeWhy it failsFixUsing lo.Contains when slices.Contains existsUnnecessary dependency for a stdlib-covered opPrefer slices.Contains/ slices.Sort since Go 1.21+ and slices.Collect(maps.Keys(m)) since Go 1.23+ when a key slice is neededUsing lop.Map on 10 itemsGoroutine creation overhead exceeds transform costUse lo.Map — lop benefits start at ~1000+ items for CPU-bound workAssuming lo.Filter modifies the inputlo is immutable by default — it returns a new sliceUse lom.Filter if you explicitly need in-place mutationUsing lo.Must in production code pathsMust panics on error — fine in tests and init, dangerous in request handlersUse the non-Must variant and handle the errorChaining many eager transforms on large dataEach step allocates an intermediate sliceUse loi (lazy iterators) to avoid intermediate allocations
slices.Contains and slices.Sort (Go 1.21+) carry no dependency; maps.Keys is Go 1.23+ and returns an iterator, so use slices.Collect(maps.Keys(m)) when you need a slice. Use lo for transforms the stdlib doesn't offer (Map, Filter, Reduce, GroupBy, Chunk, Flatten)lo.Filter → lo.Map → lo.GroupBy instead of writing nested loops. Each function is a building blocklo to lom/ lop only after go tool pprof confirms allocation or CPU as the bottlenecklo.MapErr over lo.Map + manual error collection. Error variants stop early and propagate cleanlylo.Must only in tests and init — in production, handle errors explicitlyFunctionWhat it doeslo.MapTransform each elementlo.Filter / lo.RejectKeep / remove elements matching predicatelo.ReduceFold elements into a single valuelo.ForEachSide-effect iterationlo.GroupByGroup elements by keylo.ChunkSplit into fixed-size batcheslo.FlattenFlatten nested slices one levello.Uniq / lo.UniqByRemove duplicateslo.Find / lo.FindOrElseFirst match or defaultlo.Contains / lo.Every / lo.SomeMembership testslo.Keys / lo.ValuesExtract map keys or valueslo.PickBy / lo.OmitByFilter map entrieslo.Zip2 / lo.Unzip2Pair/unpair two sliceslo.Range / lo.RangeFromGenerate number sequenceslo.Ternary / lo.IfInline conditionalslo.ToPtr / lo.FromPtrPointer helperslo.Must / lo.TryPanic-on-error / recover-as-boollo.Async / lo.AttemptAsync execution / retry with backofflo.Debounce / lo.ThrottleRate limitinglo.ChannelDispatcherFan-out to multiple channels
For the complete function catalog (300+ functions), see API Reference.
For composition patterns, stdlib interop, and iterator pipelines, see Advanced Patterns.
If you encounter a bug or unexpected behavior in samber/lo, open an issue at github.com/samber/lo/issues.
samber/cc-skills-golang@golang-samber-ro skill for reactive/streaming pipelines over infinite event streams ( samber/ro package)samber/cc-skills-golang@golang-samber-mo skill for monadic types (Option, Result, Either) that compose with lo transformssamber/cc-skills-golang@golang-data-structures skill for choosing the right underlying data structuresamber/cc-skills-golang@golang-performance skill for profiling methodology before switching to lom/ lop