← 返回 Skills 市场
samber

Golang Samber Lo

作者 Samuel Berthe · GitHub ↗ · v1.0.3 · MIT-0
cross-platform ✓ 安全检测通过
179
总下载
0
收藏
1
当前安装
3
版本数
在 OpenClaw 中安装
/install golang-samber-lo
功能描述
Functional programming helpers for Golang using samber/lo — 500+ type-safe generic functions for slices, maps, channels, strings, math, tuples, and concurren...
使用说明 (SKILL.md)

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

go get github.com/samber/lo
Package Import Alias Go version
Core (immutable) github.com/samber/lo lo 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
lo Default for all transforms Allocates new collections (safe, predictable)
lop 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
  • lom breaks immutability — only use when allocation pressure is measured, never assumed
  • loi 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

// ✓ 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)
}

Filter + Reduce

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

byStatus := lo.GroupBy(tasks, func(t Task, _ int) string {
    return t.Status
})
// map[string][]Task{"open": [...], "closed": [...]}

Error variant — stop on first error

results, err := lo.MapErr(urls, func(url string, _ int) (Response, error) {
    return http.Get(url)
})

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.Maplop 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 availableslices.Contains, slices.Sort, maps.Keys carry no dependency. Use lo for transforms the stdlib doesn't offer (Map, Filter, Reduce, GroupBy, Chunk, Flatten)
  2. Compose lo functions — chain lo.Filterlo.Maplo.GroupBy instead of writing nested loops. Each function is a building block
  3. Profile before optimizing — switch from lo to lom/lop only after go tool pprof confirms allocation or CPU as the bottleneck
  4. Use error variants — prefer lo.MapErr over lo.Map + manual error collection. Error variants stop early and propagate cleanly
  5. Use lo.Must only in tests and init — in production, handle errors explicitly

Quick Reference

Function What it does
lo.Map Transform each element
lo.Filter / lo.Reject 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/lop
安全使用建议
This skill is a documentation/assistant for the samber/lo Go library and appears internally consistent. It's instruction-only and doesn't request secrets or perform installs. Before installing, verify the homepage/source (https://github.com/samber/cc-skills-golang) to ensure it matches the upstream library you expect. Be aware that the skill is allowed to read and modify repository files (Read/Edit/Write, Bash/git commands) — appropriate for coding tasks but review any changes it proposes. Finally, if you plan to add samber/lo as a dependency to production code, review and pin the library version and run your usual security and dependency checks (vulnerability scanner, code review, and CI tests).
功能分析
Type: OpenClaw Skill Name: golang-samber-lo Version: 1.0.3 The skill bundle provides comprehensive documentation and guidance for the legitimate 'samber/lo' Go utility library. It includes detailed API references, usage patterns, and evaluation cases (evals/evals.json) designed to ensure the AI agent follows best practices, such as avoiding 'lo.Must' in production and preferring the standard library when applicable. The tool permissions in SKILL.md are appropriately restricted to Go-related development commands (e.g., go:*, git:*), and there is no evidence of malicious intent, data exfiltration, or prompt injection.
能力评估
Purpose & Capability
Name, description, and SKILL.md all describe guidance for using github.com/samber/lo. Declared requirement (go binary) and allowed tools (edit/read/write, go, git, linters) are proportionate to a coding/documentation helper.
Instruction Scope
SKILL.md contains documentation, patterns, examples and runtime instructions that keep to the library domain. It does not instruct reading unrelated system credentials. Note: allowed-tools include generic file operations (Read/Edit/Write/Glob/Grep and Bash wrappers) which permits repository file access — this is expected for a coding assistant but gives the skill broad ability to read and modify project files.
Install Mechanism
No install spec; instruction-only skill (nothing is downloaded or written during install). This minimizes supply-chain/install risk.
Credentials
The skill requests no environment variables, credentials, or config paths; that is proportionate for a docs/coding helper.
Persistence & Privilege
always is false and autonomous invocation is allowed (platform default). The skill does not request elevated persistence or to modify other skills or system-wide config.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install golang-samber-lo
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /golang-samber-lo 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.3
- Version incremented to 1.0.3 and metadata updated accordingly. - Compatibility note: Added AskUserQuestion to allowed tools. - Minor text fix: "more informations" corrected to "more information" in documentation. - No functional or feature changes; documentation only.
v1.0.1
golang-samber-lo version 1.0.1 - Added an evaluation manifest file (`evals/evals.json`). - Updated SKILL.md metadata: set version to 1.0.1 (was 1.0.0) and adjusted formatting of the description. - No breaking changes to usage or API.
v0.1.0
Initial release of golang-samber-lo skill. - Provides structured knowledge and best practices for using the samber/lo functional utilities library in Go, including Map, Filter, Reduce, GroupBy, Chunk, Flatten, and more. - Explains package variants (lo, parallel/lop, mutable/lom, iterator/loi, experimental SIMD) and guides choosing the right one based on trade-offs and performance. - Details common mistakes and best practices for efficient, idiomatic usage alongside the Go standard library. - Includes quick reference examples and installation guidance. - Not intended for streaming pipelines—refer to golang-samber-ro for such use cases.
元数据
Slug golang-samber-lo
版本 1.0.3
许可证 MIT-0
累计安装 1
当前安装数 1
历史版本数 3
常见问题

Golang Samber Lo 是什么?

Functional programming helpers for Golang using samber/lo — 500+ type-safe generic functions for slices, maps, channels, strings, math, tuples, and concurren... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 179 次。

如何安装 Golang Samber Lo?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install golang-samber-lo」即可一键安装,无需额外配置。

Golang Samber Lo 是免费的吗?

是的,Golang Samber Lo 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Golang Samber Lo 支持哪些平台?

Golang Samber Lo 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Golang Samber Lo?

由 Samuel Berthe(@samber)开发并维护,当前版本 v1.0.3。

💬 留言讨论