Skip to main content
Help improve this documentation

This documentation is still new and evolving. If you spot any mistakes, unclear explanations, or missing details, please open an issue.

Your feedback helps us improve!

sort operatorsโ€‹

This page lists all operators available in the sort sub-package of ro.

Installโ€‹

First, import the sub-package in your project:

go get -u github.com/samber/ro/plugins/sort
  • Sorts ordered values (loads all into memory).

    import (
    "github.com/samber/ro"
    rosort "github.com/samber/ro/plugins/sort"
    )

    obs := ro.Pipe[int, int](
    ro.Just(3, 1, 4, 1, 5, 9, 2, 6),
    rosort.Sort[int](func(a, b int) int { return a - b }),
    )

    sub := obs.Subscribe(ro.PrintObserver[int]())
    defer sub.Unsubscribe()

    // Next: 1
    // Next: 1
    // Next: 2
    // Next: 3
    // Next: 4
    // Next: 5
    // Next: 6
    // Next: 9
    // Completed
    Prototype:
    func Sort[T cmp.Ordered](cmp func(a, b T) int)
  • Sorts values using comparison function.

    import (
    "strings"

    "github.com/samber/ro"
    rosort "github.com/samber/ro/plugins/sort"
    )

    obs := ro.Pipe[string, string](
    ro.Just("banana", "apple", "cherry"),
    rosort.SortFunc[string](func(a, b string) int {
    return strings.Compare(a, b)
    }),
    )

    sub := obs.Subscribe(ro.PrintObserver[string]())
    defer sub.Unsubscribe()

    // Next: apple
    // Next: banana
    // Next: cherry
    // Completed
    Prototype:
    func SortFunc[T comparable](cmp func(a, b T) int)
  • Sorts elements using a stable sort with custom comparison function. Stable sort preserves the relative order of equal elements.

    import (
    "github.com/samber/ro"
    rosort "github.com/samber/ro/plugins/sort"
    )

    type Person struct {
    Name string
    Age int
    }

    people := []Person{
    {"Alice", 25},
    {"Bob", 30},
    {"Charlie", 25},
    {"David", 30},
    }

    obs := ro.Pipe[Person, Person](
    ro.Just(people...),
    rosort.SortStableFunc(func(a, b Person) int {
    if a.Age != b.Age {
    return a.Age - b.Age // Sort by age
    }
    return 0 // Keep original order for same age
    }),
    )

    sub := obs.Subscribe(ro.PrintObserver[Person]())
    defer sub.Unsubscribe()

    // Next: {Alice 25}
    // Next: {Charlie 25} // Same age as Alice, original order preserved
    // Next: {Bob 30}
    // Next: {David 30} // Same age as Bob, original order preserved
    // Completed
    Similar:
    Prototype:
    func SortStableFunc[T comparable](cmp func(a, b T) int)