Skip to content

unsafe-risk/golib

Repository files navigation

golib

Modern generic utilities and collections for Go (1.27+)

This library provides practical, ergonomic generic types and collections that take full advantage of Go 1.27's generic methods. It includes Option, Result, and various collection types with clean, chainable APIs.

nums := concurrent.SliceOf(1, 2, 3, 4, 5).
    Filter(func(x int) bool { return x > 2 }).
    Map(func(x int) string { return fmt.Sprintf("#%d", x) })

Packages

  • github.com/unsafe-risk/golib/optionOption[T]
  • github.com/unsafe-risk/golib/resultResult[T, E]
  • github.com/unsafe-risk/golib/concurrentSlice[T], List[T], concurrent Map and Set

Zero dependencies. Designed from the ground up for Go 1.27+.

Quick Start

import (
    "github.com/unsafe-risk/golib/option"
    "github.com/unsafe-risk/golib/result"
    "github.com/unsafe-risk/golib/concurrent"
)

func main() {
    // Option & Result
    opt := option.Some(42)
    doubled := opt.Map(func(x int) int { return x * 2 })
    fmt.Println(doubled.UnwrapOr(0)) // 84

    res := result.Try(func() (int, error) {
        return strconv.Atoi("42")
    }).Map(func(i int) int { return i * 2 })
    fmt.Println(res.UnwrapOr(-1))

    // Collections
    nums := concurrent.SliceOf(1, 2, 3, 4, 5).
        Filter(func(x int) bool { return x > 2 }).
        Map(func(x int) string { return fmt.Sprintf("#%d", x) })

    m := concurrent.NewMap[string, int]()
    m.Store("score", 100)
}

Advanced Combinators

The library provides many powerful functional-style methods across its types:

Control Flow

  • Match(onSome, onNone) / Match(onOk, onErr)
  • Fold — transform Option/Result into another type without panics

Logical Combinators

  • And, Or, Xor (Option)
  • And, Or (Result)

Transformations

  • MapOr, MapOrElse
  • Filter, Contains
  • Flatten (for nested Option[Option[T]] or Result[Result[T,E], E])
  • TransposeResult[Option[T], E]Option[Result[T, E]]

Error Integration

  • AsError() + Error() for seamless errors.Is / errors.As support
  • ExpectErr, MapErr

Example using Match:

res.Match(
    func(v int) { fmt.Println("Success:", v) },
    func(e error) { fmt.Println("Error:", e) },
)

Error Handling with Go stdlib

if errors.Is(myResult.AsError(), mySentinel) {
    // handle specific error
}

var target *MyError
if errors.As(myResult.AsError(), &target) {
    // ...
}

Result[T, error] also implements the error interface when it is in the Err state.

Data Structures

In addition to Option and Result, this library provides a small set of generic data structures with rich functional operations (powered by Go 1.27+ generic methods):

import "github.com/unsafe-risk/golib/concurrent"

// Fluent slice operations (powered by Go 1.27+ generic methods)
nums := concurrent.SliceOf(1, 2, 3, 4, 5).
    Filter(func(x int) bool { return x > 2 }).
    Map(func(x int) string { return fmt.Sprintf("#%d", x) })

evens, odds := nums.Partition(func(x int) bool { return x%2 == 0 })

// Doubly linked list
l := concurrent.NewList[string]()
l.PushBack("hello")
l.PushFront("world")

// Thread-safe Map and Set (backed by sync.Map)
m := concurrent.NewMap[string, int]()
m.Store("score", 100)

s := concurrent.NewSet[int]()
s.Add(42)
s.Contains(42) // true

What's inside concurrent

  • Slice[T] — Rich generic slice powered by Go 1.27+ generic methods.
    • Functional: Map, Filter, Reduce, Find, Any, All, Partition, GroupBy
    • Sorting: Sort(less func(a, b T) bool)
  • List[T] — Doubly linked list.
    • Basic: PushFront/PushBack, Pop*, ForEach, Clear
    • Functional: Map, Filter, Reduce, Find, Any, All, Partition, GroupBy
  • Map[K comparable, V any] — Generic concurrent map based on sync.Map.
    • Thread-safe operations + MapValues, Filter, ForEach, Keys, Values
  • Set[T comparable] — Generic concurrent set based on sync.Map.
    • Thread-safe operations + Filter, Map, Partition, ForEach

Design Principles

  • Generic methods first — Clean [U any] methods thanks to Go 1.27+
  • Zero value safety — Types like Option[T] have predictable zero-value behavior
  • Explicit & predictable — Panics on Unwrap/Expect are intentional and documented
  • Excellent Go interop — Plays well with errors, json, existing (T, error) APIs
  • Focused scope — Not a full FP library, but extremely strong at what it does

Status

Solid foundation is complete:

  • Option[T] and Result[T, E] with rich functional methods
  • Slice[T], List[T], concurrent Map[K, V], and Set[T] under the concurrent package
  • Strong errors.Is/As support and comprehensive test coverage with race detection

See the godoc Example tests in each package for more real-world usage patterns.

Why not samber/mo?

samber/mo is great and broader in scope. This library is more focused, strictly targets Go 1.27+, and emphasizes practical, idiomatic Go APIs built on top of modern generics. It also leaves room for future unsafe-based optimizations (hence the org name).

Use whichever fits your project better.

Roadmap

High-value upcoming work:

  • Full JSON marshaling/unmarshaling
  • Benchmarks + comparison against raw Go and other libraries
  • More real-world usage examples
  • (Optional) unsafe size optimizations for pointer-heavy cases

Built with ❤️ for developers who miss ?, map, and_then, and transpose in Go.

About

This library provides practical, ergonomic generic types and collections

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages