golang-samber-lo

โดย samber

ตัวช่วยการเขียนโปรแกรมเชิงฟังก์ชันสำหรับ Golang โดยใช้ samber/lo — ฟังก์ชันเจนเนอริกที่ปลอดภัยต่อชนิดข้อมูลกว่า 500 รายการสำหรับ slices, maps, channels, strings, math, tuples และการทำงานพร้อมกัน (Map, Filter, Reduce, GroupBy, Chunk, Flatten, Find, Uniq ฯลฯ) แพ็กเกจหลักแบบ immutable (lo), รูปแบบ concurrent (lo/parallel หรือ lop), การเปลี่ยนแปลงในที่ (lo/mutable หรือ lom), lazy iterators (lo/it หรือ loi สำหรับ Go 1.23+) และ SIMD ทดลอง (lo/exp/simd) ใช้เมื่อกำลังใช้งานหรือนำ samber/lo มาใช้ เมื่อโค้ดเบสนำเข้า...

npx skills add https://github.com/samber/cc-skills-golang --skill golang-samber-lo

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
PackageImportAliasGo version
Core (immutable)github.com/samber/lolo1.18+
Parallelgithub.com/samber/lo/parallellop1.18+
Mutablegithub.com/samber/lo/mutablelom1.18+
Iteratorgithub.com/samber/lo/itloi1.23+
SIMD (experimental)github.com/samber/lo/exp/simd1.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.

PackageUse whenTrade-off
loDefault for all transformsAllocates new collections (safe, predictable)
lopCPU-bound work on large datasets (1000+ items)Goroutine overhead; not for I/O or small slices
lomHot path confirmed by pprof -alloc_objectsMutates input — caller must understand side effects
loiLarge datasets with chained transforms (Go 1.23+)Lazy evaluation saves memory but adds iterator complexity
simdNumeric 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

MistakeWhy it failsFix
Using 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 needed
Using lop.Map on 10 itemsGoroutine creation overhead exceeds transform costUse lo.Maplop benefits start at ~1000+ items for CPU-bound work
Assuming lo.Filter modifies the inputlo is immutable by default — it returns a new sliceUse lom.Filter if you explicitly need in-place mutation
Using 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 error
Chaining many eager transforms on large dataEach step allocates an intermediate sliceUse loi (lazy iterators) to avoid intermediate allocations

Best Practices

  1. Prefer stdlib when availableslices.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)
  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

FunctionWhat it does
lo.MapTransform each element
lo.Filter / lo.RejectKeep / remove elements matching predicate
lo.ReduceFold elements into a single value
lo.ForEachSide-effect iteration
lo.GroupByGroup elements by key
lo.ChunkSplit into fixed-size batches
lo.FlattenFlatten nested slices one level
lo.Uniq / lo.UniqByRemove duplicates
lo.Find / lo.FindOrElseFirst match or default
lo.Contains / lo.Every / lo.SomeMembership tests
lo.Keys / lo.ValuesExtract map keys or values
lo.PickBy / lo.OmitByFilter map entries
lo.Zip2 / lo.Unzip2Pair/unpair two slices
lo.Range / lo.RangeFromGenerate number sequences
lo.Ternary / lo.IfInline conditionals
lo.ToPtr / lo.FromPtrPointer helpers
lo.Must / lo.TryPanic-on-error / recover-as-bool
lo.Async / lo.AttemptAsync execution / retry with backoff
lo.Debounce / lo.ThrottleRate limiting
lo.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.

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

Skills เพิ่มเติมจาก samber

golang-code-style
samber
Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).
developmentcode-review
golang-testing
samber
Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky/slow tests. For testify-specific APIs see `samber/cc-skills-golang@golang-stretchr-testify`; for measurement methodology see...
developmenttestingcode-review
golang-design-patterns
samber
รูปแบบการออกแบบ Go ที่เป็นธรรมชาติ — ตัวเลือกเชิงฟังก์ชัน, คอนสตรัคเตอร์, การไหลของข้อผิดพลาดและการเรียงลำดับ, การจัดการทรัพยากรและวงจรชีวิต, การปิดระบบอย่างนุ่มนวล, ความยืดหยุ่น, สถาปัตยกรรม, การฉีด dependencies, การจัดการข้อมูล, การสตรีม และอื่นๆ ใช้เมื่อเลือกอย่างชัดเจนระหว่างรูปแบบสถาปัตยกรรม, การใช้ตัวเลือกเชิงฟังก์ชัน, การออกแบบ API ของคอนสตรัคเตอร์, การตั้งค่าการปิดระบบอย่างนุ่มนวล, การใช้รูปแบบความยืดหยุ่น, หรือการถามว่ารูปแบบ Go ที่เป็นธรรมชาติใดเหมาะกับปัญหาเฉพาะ
developmentdesigncode-review
golang-error-handling
samber
Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops`...
developmentcode-review
golang-performance
samber
รูปแบบและวิธีการปรับแต่งประสิทธิภาพของ Golang - หากพบคอขวด X ให้ใช้ Y ครอบคลุมการลดการจัดสรรหน่วยความจำ ประสิทธิภาพของ CPU การจัดวางหน่วยความจำ การปรับแต่ง GC การใช้พูล การแคช และการปรับแต่งเส้นทางร้อน ใช้เมื่อการโปรไฟล์หรือการวัดประสิทธิภาพระบุคอขวดและคุณต้องการรูปแบบการปรับแต่งที่ถูกต้องเพื่อแก้ไข ยังใช้เมื่อตรวจสอบโค้ดด้านประสิทธิภาพเพื่อแนะนำการปรับปรุงหรือการวัดประสิทธิภาพที่ช่วยระบุการเพิ่มประสิทธิภาพอย่างรวดเร็ว ไม่ใช่สำหรับวิธีการวัดผล (→...
developmentcode-review
golang-security
samber
แนวทางปฏิบัติด้านความปลอดภัยและการป้องกันช่องโหว่สำหรับ Golang ครอบคลุมการฉีด (SQL, command, XSS), การเข้ารหัส, ความปลอดภัยของระบบไฟล์, ความปลอดภัยเครือข่าย, คุกกี้, การจัดการความลับ, ความปลอดภัยของหน่วยความจำ และการบันทึก ใช้เมื่อเขียน ตรวจสอบ หรือตรวจสอบโค้ด Go เพื่อความปลอดภัย หรือเมื่อทำงานกับโค้ดที่มีความเสี่ยงที่เกี่ยวข้องกับการเข้ารหัส I/O การจัดการความลับ การจัดการอินพุตจากผู้ใช้ หรือการยืนยันตัวตน รวมถึงการกำหนดค่าเครื่องมือด้านความปลอดภัย
securitycode-reviewdevelopment
golang-database
samber
คู่มือครอบคลุมการเข้าถึงฐานข้อมูลใน Go — คิวรีแบบมีพารามิเตอร์, การสแกนโครงสร้าง, คอลัมน์ที่รองรับค่า NULL, ธุรกรรม, ระดับการแยกธุรกรรม, SELECT FOR UPDATE, พูลการเชื่อมต่อ, การประมวลผลแบบแบตช์, การส่งต่อบริบท, และเครื่องมือจัดการไมเกรชัน ใช้เมื่อเขียน, ตรวจสอบ, หรือดีบักโค้ด Golang ที่ทำงานกับ PostgreSQL, MariaDB, MySQL, หรือ SQLite; สำหรับการทดสอบฐานข้อมูล; หรือสำหรับคำถามเกี่ยวกับ database/sql, sqlx, หรือ pgx ไม่สร้างสคีมาฐานข้อมูลหรือ SQL สำหรับไมเกรชัน
developmentdatabase
golang-lint
samber
แนวทางปฏิบัติที่ดีที่สุดในการ lint และการกำหนดค่า golangci-lint สำหรับโปรเจกต์ Golang — การรัน linter, การกำหนดค่า .golangci.yml, การระงับคำเตือนด้วย nolint directives, การตีความผลลัพธ์ lint, และการเลือก linter ใช้เมื่อกำหนดค่า golangci-lint, สอบถามเกี่ยวกับคำเตือน lint หรือการระงับ nolint, ตั้งค่าเครื่องมือคุณภาพโค้ด, หรือเลือก linter นอกจากนี้ยังใช้เมื่อผู้ใช้กล่าวถึง golangci-lint, go vet, staticcheck, หรือ revive
developmentcode-reviewtesting