Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
L

lo

> 编程语言
Open source

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

21.4K stars0 likes1 views
WebsiteGitHub

About

💥 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

bash
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:

go
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:

go
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.

go
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.

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

[play]

go
// 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.

go
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:

go
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"}
go
// 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.

go
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.

go
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.

go
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

Issues· 231 open

View all issuesOpen on GitHub
  • #877

    Add a zip helper that stops at the shortest input

    breaking changeUpdated Sep 27, 2026
  • #803

    Experimental support of SIMD (go 1.27+)

    Updated Sep 9, 2026
  • #948

    Func lo.SnakeCase adds underscore before digits

    Updated Aug 25, 2026
  • #973

    Is there a function to find if one or more elements of a slice matches one or more elements of another slice using func?

    Updated Aug 24, 2026
  • #974

    Capitalize upper cases format characters

    Updated Aug 18, 2026
  • #578

    Road to V2

    breaking changespecUpdated Aug 6, 2026
  • #805

    Rename SeqToChannel2 to Seq2ToChannel

    breaking changeUpdated Jul 29, 2026
  • #902

    feat: IsNilOrEmpty method

    Updated Jul 16, 2026
  • #298

    How about add a Join function?

    Updated Jun 21, 2026
  • #702

    Doc: run linter on markdown code blocks

    Updated May 8, 2026

> Tags

Goconstraintscontractfilterablefoldable

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 1, 2026
Category编程语言
PricingOpen source

> Related tools

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