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.
samber/lo — Functional Utilities for Go
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. Context7 can help as a discoverability platform.
Why samber/lo
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:
- - Type-safe generics — no
interface{} casts, no reflection, compile-time checking, no interface boxing overhead - Immutable by default — returns new collections, safe for concurrent reads, easier to reason about
- Composable — functions take and return slices/maps, so they chain without wrapper types
- Zero dependencies — only Go stdlib, no transitive dependency risk
- Progressive complexity — start with
lo, upgrade to lop/lom/loi only when profiling demands it - Error variants — most functions have
Err suffixes (MapErr, FilterErr, ReduceErr) that stop on first error
Installation
CODEBLOCK0
| Package | Import | Alias | Go version |
|---|
| Core (immutable) | INLINECODE16 | INLINECODE17 | 1.18+ |
| Parallel |
github.com/samber/lo/parallel |
lop | 1.18+ |
| Mutable |
github.com/samber/lo/mutable |
lom | 1.18+ |
| Iterator |
github.com/samber/lo/it |
loi | 1.23+ |
| SIMD (experimental) |
github.com/samber/lo/exp/simd | — | 1.25+ (amd64 only) |
Choose the Right Package
Start with lo. Move to other packages only when profiling shows a bottleneck or when lazy evaluation is explicitly needed.
| Package | Use when | Trade-off |
|---|
| INLINECODE26 | Default for all transforms | Allocates new collections (safe, predictable) |
| INLINECODE27 |
CPU-bound work on large datasets (1000+ items) | Goroutine overhead; not for I/O or small slices |
|
lom | Hot path confirmed by
pprof -alloc_objects | Mutates input — caller must understand side effects |
|
loi | Large datasets with chained transforms (Go 1.23+) | Lazy evaluation saves memory but adds iterator complexity |
|
simd | Numeric 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 instead - INLINECODE34 breaks immutability — only use when allocation pressure is measured, never assumed
- INLINECODE35 eliminates intermediate allocations in chains like
Map → Filter → Take by evaluating lazily - For reactive/streaming pipelines over infinite event streams, → see
samber/cc-skills-golang@golang-samber-ro skill + samber/ro package
For detailed package comparison and decision flowchart, see Package Guide.
Core Patterns
Transform a slice
CODEBLOCK1
Filter + Reduce
CODEBLOCK2
GroupBy
CODEBLOCK3
Error variant — stop on first error
CODEBLOCK4
Common Mistakes
| Mistake | Why it fails | Fix |
|---|
Using lo.Contains when slices.Contains exists | Unnecessary dependency for a stdlib-covered op | Prefer slices.Contains, slices.Sort, maps.Keys since Go 1.21+ |
Using lop.Map on 10 items |
Goroutine creation overhead exceeds transform cost | Use
lo.Map —
lop benefits start at ~1000+ items for CPU-bound work |
| Assuming
lo.Filter modifies the input |
lo is immutable by default — it returns a new slice | Use
lom.Filter if you explicitly need in-place mutation |
| Using
lo.Must in production code paths |
Must panics on error — fine in tests and init, dangerous in request handlers | Use the non-Must variant and handle the error |
| Chaining many eager transforms on large data | Each step allocates an intermediate slice | Use
loi (lazy iterators) to avoid intermediate allocations |
Best Practices
- 1. Prefer stdlib when available —
slices.Contains, slices.Sort, maps.Keys carry no dependency. Use lo for transforms the stdlib doesn't offer (Map, Filter, Reduce, GroupBy, Chunk, Flatten) - Compose lo functions — chain
lo.Filter → lo.Map → lo.GroupBy instead of writing nested loops. Each function is a building block - Profile before optimizing — switch from
lo to lom/lop only after go tool pprof confirms allocation or CPU as the bottleneck - Use error variants — prefer
lo.MapErr over lo.Map + manual error collection. Error variants stop early and propagate cleanly - Use
lo.Must only in tests and init — in production, handle errors explicitly
Quick Reference
| Function | What it does |
|---|
| INLINECODE67 | Transform each element |
| INLINECODE68 / INLINECODE69 |
Keep / remove elements matching predicate |
|
lo.Reduce | Fold elements into a single value |
|
lo.ForEach | Side-effect iteration |
|
lo.GroupBy | Group elements by key |
|
lo.Chunk | Split into fixed-size batches |
|
lo.Flatten | Flatten nested slices one level |
|
lo.Uniq /
lo.UniqBy | Remove duplicates |
|
lo.Find /
lo.FindOrElse | First match or default |
|
lo.Contains /
lo.Every /
lo.Some | Membership tests |
|
lo.Keys /
lo.Values | Extract map keys or values |
|
lo.PickBy /
lo.OmitBy | Filter map entries |
|
lo.Zip2 /
lo.Unzip2 | Pair/unpair two slices |
|
lo.Range /
lo.RangeFrom | Generate number sequences |
|
lo.Ternary /
lo.If | Inline conditionals |
|
lo.ToPtr /
lo.FromPtr | Pointer helpers |
|
lo.Must /
lo.Try | Panic-on-error / recover-as-bool |
|
lo.Async /
lo.Attempt | Async execution / retry with backoff |
|
lo.Debounce /
lo.Throttle | Rate limiting |
|
lo.ChannelDispatcher | Fan-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.
Cross-References
- - → See
samber/cc-skills-golang@golang-samber-ro skill for reactive/streaming pipelines over infinite event streams (samber/ro package) - → See
samber/cc-skills-golang@golang-samber-mo skill for monadic types (Option, Result, Either) that compose with lo transforms - → See
samber/cc-skills-golang@golang-data-structures skill for choosing the right underlying data structure - → See
samber/cc-skills-golang@golang-performance skill for profiling methodology before switching to lom/ INLINECODE107
技能名称: golang-samber-lo
详细描述:
角色: 你是一位Go工程师,更倾向于使用声明式集合转换而非手动循环。你会使用lo来消除样板代码,但你知道何时标准库已足够,以及何时应升级到lop、lom或loi。
samber/lo — Go语言的函数式工具库
受Lodash启发、以泛型为先的工具库,提供500多个类型安全的辅助函数,涵盖切片、映射、字符串、数学、通道、元组和并发。零外部依赖。默认不可变。
官方资源:
本技能并非详尽无遗。请参考库文档和代码示例获取更多信息。Context7可作为发现平台提供帮助。
为什么选择samber/lo
Go的标准库slices和maps包涵盖了约10个基本辅助函数(排序、包含、键)。其他所有功能——Map、Filter、Reduce、GroupBy、Chunk、Flatten、Zip——都需要手动编写for循环。lo填补了这一空白:
- - 类型安全的泛型 — 无需interface{}类型转换,无反射,编译时检查,无接口装箱开销
- 默认不可变 — 返回新集合,并发读取安全,更易于推理
- 可组合 — 函数接收并返回切片/映射,因此无需包装器类型即可链式调用
- 零依赖 — 仅依赖Go标准库,无传递性依赖风险
- 渐进式复杂度 — 从lo开始,仅在性能分析要求时升级到lop/lom/loi
- 错误变体 — 大多数函数带有Err后缀(MapErr、FilterErr、ReduceErr),在遇到第一个错误时停止
安装
bash
go get github.com/samber/lo
| 包 | 导入路径 | 别名 | Go版本 |
|---|
| 核心(不可变) | github.com/samber/lo | lo | 1.18+ |
| 并行 |
github.com/samber/lo/parallel | lop | 1.18+ |
| 可变 | github.com/samber/lo/mutable | lom | 1.18+ |
| 迭代器 | github.com/samber/lo/it | loi | 1.23+ |
| SIMD(实验性) | github.com/samber/lo/exp/simd | — | 1.25+(仅amd64) |
选择合适的包
从lo开始。仅在性能分析显示瓶颈或明确需要惰性求值时,才迁移到其他包。
| 包 | 使用场景 | 权衡 |
|---|
| lo | 所有转换的默认选择 | 分配新集合(安全、可预测) |
| lop |
大数据集(1000+项)上的CPU密集型工作 | 协程开销;不适用于I/O或小切片 |
| lom | 经pprof -alloc_objects确认的热路径 | 修改输入——调用者必须理解副作用 |
| loi | 带有链式转换的大数据集(Go 1.23+) | 惰性求值节省内存,但增加了迭代器复杂度 |
| simd | 基准测试后的数值批量操作(实验性) | API不稳定,可能在版本间发生变化 |
关键规则:
- - lop用于CPU并行,而非I/O并发——对于I/O扇出,请使用errgroup
- lom破坏了不可变性——仅在测量到分配压力时使用,切勿假设
- loi通过惰性求值消除了Map → Filter → Take等链式调用中的中间分配
- 对于无限事件流上的响应式/流式管道,→ 参见samber/cc-skills-golang@golang-samber-ro技能 + samber/ro包
有关详细的包比较和决策流程图,请参见包指南。
核心模式
转换切片
go
// ✓ lo — 声明式,类型安全
names := lo.Map(users, func(u User, _ int) string {
return u.Name
})
// ✗ 手动 — 样板代码,易出错
names := make([]string, 0, len(users))
for _, u := range users {
names = append(names, u.Name)
}
Filter + Reduce
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,
)
GroupBy
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)
})
常见错误
| 错误 | 失败原因 | 修复 |
|---|
| 在slices.Contains已存在时使用lo.Contains | 为标准库已覆盖的操作引入不必要的依赖 | 自Go 1.21+起,优先使用slices.Contains、slices.Sort、maps.Keys |
| 对10个项使用lop.Map |
协程创建开销超过转换成本 | 使用lo.Map——lop的优势从约1000+项的CPU密集型工作开始体现 |
| 假设lo.Filter会修改输入 | lo默认不可变——它返回一个新切片 | 如果明确需要原地修改,使用lom.Filter |
| 在生产代码路径中使用lo.Must | Must在出错时会panic——在测试和初始化中没问题,在请求处理程序中很危险 | 使用非Must变体并处理错误 |
| 在大数据上链式调用多个急切转换 | 每一步都会分配一个中间切片 | 使用loi(惰性迭代器)避免中间分配 |
最佳实践
- 1. 优先使用标准库(当可用时) — slices.Contains、slices.Sort、maps.Keys不引入依赖。对于标准库未提供的转换(Map、Filter、Reduce、GroupBy、Chunk、Flatten),使用lo
- 组合lo函数 — 链式调用lo.Filter → lo.Map → lo.GroupBy,而不是编写嵌套循环。每个函数都是一个构建块
- 先分析再优化 — 仅在go tool pprof确认分配或CPU是瓶颈后,再从lo切换到lom/lop
- 使用错误变体 — 优先使用lo.MapErr而非lo.Map + 手动错误收集。错误变体会提前停止并干净地传播
- 仅在测试和初始化中使用lo.Must — 在生产环境中,显式处理错误
快速参考
| 函数 | 功能 |
|---|
| lo.Map | 转换每个元素 |
| lo.Filter / lo.Reject |
保留/移除匹配谓词的元素 |
| lo.Reduce | 将元素折叠为单个值 |
| lo.ForEach | 副作用迭代 |
| lo.GroupBy | 按键对元素分组 |
| lo.Chunk | 分割成固定大小的批次 |
| lo.Flatten | 将嵌套切片展平一层 |
| lo.Uniq / lo.UniqBy | 移除重复项 |
| lo.Find / lo.FindOrElse | 第一个匹配项或默认值 |
| lo.Contains / lo.Every / lo.Some | 成员资格测试 |
| lo.Keys / lo.Values | 提取映射的键或值 |
| lo.PickBy / lo.OmitBy | 过滤映射条目 |
| lo.Zip2 / lo.Unzip2 | 配对/解配对两个切片 |
| lo.Range / lo.RangeFrom | 生成数字序列 |
| lo.Ternary / lo.If | 内联条件判断 |
| lo.ToPtr / lo.FromPtr | 指针辅助函数 |
| lo.Must / lo.Try | 出错时panic / 将recover转为布尔值 |
| lo.Async /