Baike.dev
All toolsTrendingOpen sourceNewsSubmit
Log in
< 返回工具列表
L

lo

> 编程语言
开源

💥 A Lodash-style Go library based on Go 1.18+ Generics (map, filter, contains, find...)

21.4K stars0 点赞0 次浏览
访问官网GitHub

工具介绍

💥 A Lodash-style Go library based on Go 1.18+ Generics (map, filter, contains, find...)

lo - Iterate over slices, maps, channels...

✨ samber/lo is a Lodash-style Go library based on Go 1.18+ Generics.

A utility library based on Go 1.18+ generics that makes it easier to work with slices, maps, strings, channels, and functions. It provides dozens of handy methods to simplify common coding tasks and improve code readability. It may look like Lodash in some aspects.

5 to 10 helpers may overlap with those from the Go standard library, in packages slices and maps. I feel this library is legitimate and offers many more valuable abstractions.

See also:

  • samber/ro: Reactive Programming for Go: declarative and composable API for event-driven applications
  • samber/do: A dependency injection toolkit based on Go 1.18+ Generics
  • samber/mo: Monads based on Go 1.18+ Generics (Option, Result, Either...)
  • samber/cc-skills-golang: AI Agent Skills for Golang

What makes it different from samber/ro?

  • lo: synchronous helpers across finite sequences (maps, slices...)
  • ro: processing of infinite data streams for event-driven scenarios

Why this name?

I wanted a short name, similar to "Lodash", and no Go package uses this name.

🚀 Install

go get github.com/samber/lo@v1

# AI Agent Skill
npx skills add https://github.com/samber/cc-skills-golang --skill golang-samber-lo

This library is v1 and follows SemVer strictly.

No breaking changes will be made to exported APIs before v2.0.0, except for experimental packages under exp/.

This library has no dependencies outside the Go standard library.

💡 Usage

You can import lo using:

import (
    "github.com/samber/lo"
    lop "github.com/samber/lo/parallel"
    lom "github.com/samber/lo/mutable"
    loi "github.com/samber/lo/it"
)

Then use one of the helpers below:

names := lo.Uniq([]string{"Samuel", "John", "Samuel"})
// []string{"Samuel", "John"}

Tips for lazy developers

I cannot recommend it, but in case you are too lazy for repeating lo. everywhere, you can import the entire library into the namespace.

import (
    . "github.com/samber/lo"
)

I take no responsibility for this junk. 😁 💩

🤠 Spec

GoDoc: godoc.org/github.com/samber/lo

Documentation: lo.samber.dev

Supported helpers for slices:

  • Filter
  • Map
  • UniqMap
  • FilterMap
  • FlatMap
  • Reduce
  • ReduceRight
  • ForEach
  • ForEachWhile
  • ForEachErr
  • Times
  • Uniq
  • UniqBy
  • IsUniq
  • IsUniqBy
  • GroupBy
  • GroupByMap
  • Chunk
  • Window
  • Sliding
  • PartitionBy
  • Flatten
  • Concat
  • Interleave
  • Shuffle
  • Reverse
  • Fill
  • Repeat
  • RepeatBy
  • KeyBy
  • SliceToMap / Associate
  • FilterSliceToMap
  • Keyify
  • Take
  • TakeWhile
  • TakeFilter
  • Drop
  • DropRight
  • DropWhile
  • DropRightWhile
  • DropByIndex
  • Reject
  • RejectMap
  • FilterReject
  • Count
  • CountBy
  • CountValues
  • CountValuesBy
  • Subset
  • Slice
  • Replace
  • ReplaceAll
  • Clone
  • Compact
  • IsSorted
  • IsSortedBy
  • Splice
  • Cut
  • CutPrefix
  • CutSuffix
  • Trim
  • TrimLeft
  • TrimPrefix
  • TrimRight
  • TrimSuffix

Supported helpers for maps:

  • Keys
  • UniqKeys
  • HasKey
  • ValueOr
  • Values
  • UniqValues
  • PickBy
  • PickByKeys
  • PickByValues
  • OmitBy
  • OmitByKeys
  • OmitByValues
  • Entries / ToPairs
  • FromEntries / FromPairs
  • Invert
  • Assign (merge of maps)
  • ChunkEntries
  • MapKeys
  • MapValues
  • MapEntries
  • MapToSlice
  • FilterMapToSlice
  • FilterKeys
  • FilterValues

Supported math helpers:

  • Range / RangeFrom / RangeWithSteps
  • Clamp
  • Sum
  • SumBy
  • Product
  • ProductBy
  • Mean
  • MeanBy
  • Mode

Supported helpers for strings:

  • RandomString
  • Substring
  • ChunkString
  • RuneLength
  • PascalCase
  • CamelCase
  • KebabCase
  • SnakeCase
  • Words
  • Capitalize
  • Ellipsis

Supported helpers for tuples:

  • T2 -> T9
  • Unpack2 -> Unpack9
  • Zip2 -> Zip9
  • ZipBy2 -> ZipBy9
  • Unzip2 -> Unzip9
  • UnzipBy2 -> UnzipBy9
  • CrossJoin2 -> CrossJoin2
  • CrossJoinBy2 -> CrossJoinBy2

Supported helpers for time and duration:

  • Duration
  • Duration0 -> Duration10

Supported helpers for channels:

  • ChannelDispatcher
  • SliceToChannel
  • ChannelToSlice
  • Generator
  • Buffer
  • BufferWithContext
  • BufferWithTimeout
  • FanIn
  • FanOut

Supported intersection helpers:

  • Contains
  • ContainsBy
  • Every
  • EveryBy
  • Some
  • SomeBy
  • None
  • NoneBy
  • Intersect
  • IntersectBy
  • Difference
  • Union
  • UnionBy
  • UnionByErr
  • Without
  • WithoutBy
  • WithoutEmpty
  • WithoutNth
  • ElementsMatch
  • ElementsMatchBy

Supported search helpers:

  • IndexOf
  • LastIndexOf
  • HasPrefix
  • HasSuffix
  • Find
  • FindIndexOf
  • FindLastIndexOf
  • FindOrElse
  • FindKey
  • FindKeyBy
  • FindUniques
  • FindUniquesBy
  • FindDuplicates
  • FindDuplicatesBy
  • Min
  • MinIndex
  • MinBy
  • MinIndexBy
  • Earliest
  • EarliestBy
  • Max
  • MaxIndex
  • MaxBy
  • MaxIndexBy
  • Latest
  • LatestBy
  • First
  • FirstOrEmpty
  • FirstOr
  • Last
  • LastOrEmpty
  • LastOr
  • Nth
  • NthOr
  • NthOrEmpty
  • Sample
  • SampleBy
  • Samples
  • SamplesBy

Conditional helpers:

  • Ternary
  • TernaryF
  • If / ElseIf / Else
  • Switch / Case / Default

Type manipulation helpers:

  • IsNil
  • IsNotNil
  • ToPtr
  • Nil
  • EmptyableToPtr
  • FromPtr
  • FromPtrOr
  • ToSlicePtr
  • FromSlicePtr
  • FromSlicePtrOr
  • ToAnySlice
  • FromAnySlice
  • Empty
  • IsEmpty
  • IsNotEmpty
  • Coalesce
  • CoalesceOrEmpty
  • CoalesceSlice
  • CoalesceSliceOrEmpty
  • CoalesceMap
  • CoalesceMapOrEmpty

Function helpers:

  • Partial
  • Partial2 -> Partial5

Concurrency helpers:

  • Attempt
  • AttemptWhile
  • AttemptWithDelay
  • AttemptWhileWithDelay
  • Debounce
  • DebounceBy
  • Throttle
  • ThrottleWithCount
  • ThrottleBy
  • ThrottleByWithCount
  • Synchronize
  • Async
  • Async{0->6}
  • Transaction
  • WaitFor
  • WaitForWithContext

Error handling:

  • Validate
  • Must
  • Try
  • Try1 -> Try6
  • TryOr
  • TryOr1 -> TryOr6
  • TryCatch
  • TryWithErrorValue
  • TryCatchWithErrorValue
  • ErrorsAs
  • Assert
  • Assertf

Constraints:

  • Clonable

Filter

Iterates over a collection and returns a slice of all the elements the predicate function returns true for.

result := lo.Filter([]int{1, 2, 3, 4}, func(x int, index int) bool {
    return x%2 == 0
})
// []int{2, 4}

[play]

// Use FilterErr when the predicate can return an error
result, err := lo.FilterErr([]int{1, 2, 3, 4}, func(x int, _ int) (bool, error) {
    if x == 3 {
        return false, fmt.Errorf("number 3 is not allowed")
    }
    return x%2 == 0, nil
})
// []int(nil), error("number 3 is not allowed")

[play]

Mutable: like lo.Filter(), but the slice is updated in place.

import lom "github.com/samber/lo/mutable"

list := []int{1, 2, 3, 4}
newList := lom.Filter(list, func(x int) bool {
    return x%2 == 0
})

list
// []int{2, 4, 3, 4}

newList
// []int{2, 4}

[play]

Map

Manipulates a slice of one type and transforms it into a slice of another type:

import "github.com/samber/lo"

result1:= lo.Map([]int64{1, 2, 3, 4}, func(x int64, index int) string {
    return strconv.FormatInt(x, 10)
})
// []string{"1", "2", "3", "4"}
// Use MapErr when the transform function can return an error
result2, err := lo.MapErr([]int{1, 2, 3, 4}, func(x int, _ int) (string, error) {
    if x == 3 {
        return "", fmt.Errorf("number 3 is not allowed")
    }
    return strconv.Itoa(x), nil
})
// []string(nil), error("number 3 is not allowed")

[play]

Parallel processing: like lo.Map(), but the transform function is called in a goroutine. Results are returned in the same order.

import lop "github.com/samber/lo/parallel"

partitionedByParity := lop.Map([]int64{1, 2, 3, 4}, func(x int64, _ int) string {
    return strconv.FormatInt(x, 10)
})
// []string{"1", "2", "3", "4"}

[play]

Mutable: like lo.Map(), but the slice is updated in place.

import lom "github.com/samber/lo/mutable"

list := []int{1, 2, 3, 4}
lom.Map(list, func(x int) int {
    return x*2
})
// []int{2, 4, 6, 8}

[play]

UniqMap

Manipulates a slice and transforms it to a slice of another type with unique values.

type User struct {
    Name string
    Age  int
}
users := []User{{Name: "Alex", Age: 10}, {Name: "Alex", Age: 12}, {Name: "Bob", Age: 11}, {Name: "Alice", Age: 20}}

names := lo.UniqMap(users, func(u User, index in

核心特点

  • •samber/ro: Reactive Programming for Go: declarative and composable API for event-driven applications
  • •samber/do: A dependency injection toolkit based on Go 1.18+ Generics
  • •samber/mo: Monads based on Go 1.18+ Generics (Option, Result, Either...)
  • •samber/cc-skills-golang: AI Agent Skills for Golang
  • •lo: synchronous helpers across finite sequences (maps, slices...)
  • •ro: processing of infinite data streams for event-driven scenarios
  • •FilterMap
  • •ReduceRight
  • •ForEachWhile
  • •ForEachErr

> 标签

Goconstraintscontractfilterablefoldable

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月9日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言
Baike.dev

baike.dev helps you discover great languages, frameworks, databases, DevOps and cloud-native tools.

Quick links

  • Home
  • All tools
  • Trending
  • Open source

About

  • About us
  • Community
  • News

Contribute

Found a great developer tool? Share it with the community.

Submit a tool
© 2026 baike.dev Developer EncyclopediaUpdated daily · Discover great developer tools