Xpersona
G

golang-samber-mo

CLAWHUB · Unverified

Monadic types for Golang using samber/mo — Option, Result, Either, Future, IO, Task, and State types for type-safe nullable values, error handling, and functional composition with pipeline sub-packages. Apply when using or adopting samber/mo, when the codebase imports `github.com/samber/mo`, or when considering functional programming patterns as a safety design for Golang.

62
Rank
84
Safety
1.3k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1.3K downloads reported by the source. Last updated 10/10/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s173arkhs3131fq5jf769qq75583hdgt:golang-samber-mo
  1. Install using `clawhub skill install s173arkhs3131fq5jf769qq75583hdgt:golang-samber-mo` in an isolated environment before connecting it to live workloads.
  2. No published capability contract is available yet, so validate auth and request/response behavior manually.
  3. Review the upstream CLAWHUB listing at https://clawhub.ai/samber/golang-samber-mo before using production credentials.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-samber-mo/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

144,785 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: golang-samber-mo
description: "Monadic types for Golang using samber/mo — Option, Result, Either, Future, IO, Task, and State types for type-safe nullable values, error handling, and functional composition with pipeline sub-packages. Apply when using or adopting samber/mo, when the codebase imports `github.com/samber/mo`, or when considering functional programming patterns as a safety design for Golang."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
metadata:
  author: samber
  version: "1.1.0"
  openclaw:
    emoji: "🎭"
    homepage: https://github.com/samber/cc-skills-golang
    requires:
      bins:
        - go
    install: []
    skill-library-version: "1.16.0"
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent WebFetch mcp__context7__resolve-library-id mcp__context7__query-docs AskUserQuestion Bash(godig:*) Bash(gopls:*) LSP mcp__gopls__*
paths:
  - "**/*.go"
---

**Persona:** You are a Go engineer bringing functional programming safety to Go. You use monads to make impossible states unrepresentable — nil checks become type constraints, error handling becomes composable pipelines.

**Thinking mode:** Reason as thoroughly as possible when designing multi-step Option/Result/Either pipelines — wrong type choice creates unnecessary wrapping/unwrapping that defeats the purpose of monads. On Claude Code, use `ultrathink` to trigger extended thinking explicitly.

# samber/mo — Monads and Functional Abstractions for Go

Go 1.18+ library providing type-safe monadic types with zero dependencies. Inspired by Scala, Rust, and fp-ts.

**Official Resources:**

- [pkg.go.dev/github.com/samber/mo](https://pkg.go.dev/github.com/samber/mo)
- [github.com/samber/mo](https://github.com/samber/mo)

This skill is not exhaustive. Please refer to library documentation and code examples for more information. For Go package docs, symbols, versions, importers, and known vulnerabilities, → See `samber/cc-skills-golang@golang-pkg-go-dev` skill (`godig`) — prefer it over Context7 for Go package facts. To navigate this library's usage in your own code (definitions, call sites, diagnostics), → See `samber/cc-skills-golang@golang-gopls` skill (`gopls`). Context7 remains a fallback for docs not indexed on pkg.go.dev.

```bash
go get github.com/samber/mo
```

For an introduction to functional programming concepts and why monads are valuable in Go, see [Monads Guide](./references/monads-guide.md).

## Core Types at a Glance

| Type | Purpose | Think of it as... |
| --- | --- | --- |
| `Option[T]` | Value that may be absent | Rust's `Option`, Java's `Optional` |
| `Result[T]` | Operation that may fail | Rust's `Result<T, E>`, replaces `(T, error)` |
| `Either[L, R]` | Value of one of two types | Scala's `Either`, TypeScript discriminated union |
| `EitherX[L, R]` | Value of one of X types | Scala's `Either`, TypeScript discriminated union |
|

_meta.json

{
  "ownerId": "kn72rhnkwjfeex9wr1n7y24qa983cjn3",
  "slug": "golang-samber-mo",
  "version": "1.1.0",
  "publishedAt": 1787420818468
}

references/advanced-types.md

# Advanced Types Reference

These types are less commonly used than Option/Result/Either but provide powerful abstractions for specific scenarios.

## Type Hierarchy

```
Synchronous                    Asynchronous
-----------                    ------------
IO[T]     (no error)    →     Task[T]     (no error)    → Future[T]
IOEither[T] (with error) →     TaskEither[T] (with error) → Future[T]
```

- **IO** wraps a synchronous side-effecting computation
- **Task** wraps an asynchronous side-effecting computation (returns a Future)
- **Future** represents a value that will be available later
- **Either** variants add error handling capability

## Future[T] — Asynchronous Values

Represents a value that may not yet be available. Similar to JavaScript's Promise.

### Constructor

```go
future := mo.NewFuture(func(resolve func(int), reject func(error)) {
    // runs asynchronously
    result, err := expensiveComputation()
    if err != nil {
        reject(err)
    } else {
        resolve(result)
    }
})
```

### Chaining

```go
future.
    Then(func(v int) (int, error) {
        return v * 2, nil  // transform on success
    }).
    Catch(func(err error) (int, error) {
        return 0, err  // handle error
    }).
    Finally(func(v int, err error) (int, error) {
        // always runs, regardless of success/failure
        log.Println("Done")
        return v, err
    })
```

### Collecting Results

```go
value, err := future.Collect()    // blocks until resolved
result := future.Result()          // blocks, returns Result[T]
either := future.Either()          // blocks, returns Either[error, T]
```

### Cancellation

```go
future.Cancel()  // terminates the future chain
```

## IO[T] — Synchronous Side Effects

Wraps a function that performs side effects. The computation is lazy — it only runs when `Run()` is called. IO never fails.

### Variants by Parameter Count

```go
// No parameters
io := mo.NewIO(func() string { return "hello" })
result := io.Run()  // "hello"

// 1 parameter
io1 := mo.NewIO1(func(name string) string { return "hello " + name })
result := io1.Run("Alice")  // "hello Alice"

// 2-5 parameters (IO2, IO3, IO4, IO5)
io2 := mo.NewIO2(func(a, b int) int { return a + b })
result := io2.Run(1, 2)  // 3
```

## IOEither[T] — Synchronous Side Effects with Errors

Like IO but the computation can fail. The callback must return `Either[error, R]`, not `(R, error)`.

```go
io := mo.NewIOEither(func() mo.Either[error, string] {
    data, err := os.ReadFile("config.yaml")
    if err != nil {
        return mo.Left[error, string](err)
    }
    return mo.Right[error, string](string(data))
})

either := io.Run()  // Either[error, string]
```

### Variants by Parameter Count

```go
// 1 parameter
io1 := mo.NewIOEither1(func(path string) mo.Either[error, string] {
    data, err := os.ReadFile(path)
    if err != nil {
        return mo.Left[error, string](err)
    }
    return mo.Right[error, string](string(data))
})
either := io1.Run("confi

references/either.md

# Either[L, R] API Reference

A discriminated union representing a value of one of two possible types. By convention, Left is the "alternative" path and Right is the "primary" path, but neither implies success or failure.

## Constructors

| Function                  | Description                 |
| ------------------------- | --------------------------- |
| `mo.Left[L, R](value L)`  | Creates a left-side Either  |
| `mo.Right[L, R](value R)` | Creates a right-side Either |

## Type Checking

| Method      | Returns | Description                            |
| ----------- | ------- | -------------------------------------- |
| `IsLeft()`  | `bool`  | True if the value is on the left side  |
| `IsRight()` | `bool`  | True if the value is on the right side |

## Value Extraction

| Method | Returns | Description |
| --- | --- | --- |
| `Left()` | `(L, bool)` | Left value and whether it exists |
| `Right()` | `(R, bool)` | Right value and whether it exists |
| `MustLeft()` | `L` | Left value or panics |
| `MustRight()` | `R` | Right value or panics |
| `LeftOrElse(fallback L)` | `L` | Left value or fallback |
| `RightOrElse(fallback R)` | `R` | Right value or fallback |
| `LeftOrEmpty()` | `L` | Left value or zero value |
| `RightOrEmpty()` | `R` | Right value or zero value |
| `Unpack()` | `(L, R)` | Both values (one will be zero value) |

## Transformations

### Swap — exchange left and right

```go
e := mo.Left[string, int]("hello")
swapped := e.Swap()  // Either[int, string] — Right("hello")
```

### MapLeft / MapRight — transform one side

The callback receives the value and must return a new `Either[L, R]`:

```go
e := mo.Left[string, int]("hello")
upper := e.MapLeft(func(s string) mo.Either[string, int] {
    return mo.Left[string, int](strings.ToUpper(s))
})
// Left("HELLO")

e2 := mo.Right[string, int](42)
doubled := e2.MapRight(func(v int) mo.Either[string, int] {
    return mo.Right[string, int](v * 2)
})
// Right(84)
```

**Go limitation:** Like Option.Map and Result.Map, direct Either methods cannot change the type parameters. Use sub-package `either.MapLeft`/`either.MapRight` for type-changing transforms — see [Pipelines Reference](./pipelines.md).

### Match — pattern matching

```go
e.Match(
    func(left string) mo.Either[string, int] {
        fmt.Println("Left:", left)
        return mo.Left[string, int](left)
    },
    func(right int) mo.Either[string, int] {
        fmt.Println("Right:", right)
        return mo.Right[string, int](right)
    },
)
```

### ForEach — side effects

```go
e.ForEach(
    func(left string) { fmt.Println("Left:", left) },
    func(right int) { fmt.Println("Right:", right) },
)
```

## Either vs Result

| Feature       | Either[L, R]            | Result[T]               |
| ------------- | ----------------------- | ----------------------- |
| Left/Err type | Any type L              | Always `error`          |
| Semantics     | Two valid alternatives  | Success or failure      |
| Use case      | Cached

references/monads-guide.md

# Functional Programming and Monads in Go

## What is Functional Programming?

Functional programming (FP) treats computation as evaluation of mathematical functions. Core principles:

- **Immutability** — data doesn't change after creation; transformations produce new values
- **Pure functions** — same input always produces same output, no side effects
- **Composition** — build complex behavior by chaining simple functions
- **Types as documentation** — types express constraints and invariants

Go isn't a pure FP language, but Go 1.18+ generics make FP patterns practical. samber/mo brings the most battle-tested FP abstractions — monads — to Go.

## What is a Monad?

A monad is a design pattern (not a class or interface) that:

1. **Wraps a value** in a context (Option wraps "maybe absent", Result wraps "maybe failed")
2. **Chains operations** that transform the wrapped value without unwrapping it
3. **Handles the context automatically** — if an Option is None, Map/FlatMap skip the transformation; if a Result is Err, subsequent Maps short-circuit

Think of it as a **container with a policy**: "I hold a value, and I know what to do when operations succeed or fail."

### The Railway Metaphor

Imagine two parallel railway tracks:

- **Happy track** (top): data flows through transformations successfully
- **Error track** (bottom): once something goes wrong, the train switches to the error track and skips remaining transformations

```
Input → [Transform A] → [Transform B] → [Transform C] → Output
          ↓ (error)       (skipped)       (skipped)
       Error track ────────────────────────────────────→ Error
```

This is exactly how Result.Map and Result.FlatMap work — errors propagate automatically without explicit if/else checks.

## Why Monads Are Valuable in Go

### 1. Compile-Time Nil Safety (Option)

Go's type system doesn't distinguish "this pointer could be nil" from "this pointer is always valid". Option[T] makes this explicit:

```go
// Without mo — caller must remember to check nil
func FindUser(id string) *User { ... }  // might return nil

// With mo — the type TELLS you it might be absent
func FindUser(id string) mo.Option[User] { ... }  // caller must handle None
```

The type signature is the documentation. No nil pointer panics at runtime — the compiler forces you to handle absence.

### 2. Railway-Oriented Error Handling (Result)

Go's idiomatic error handling requires checking errors at every step:

```go
// Without mo — repetitive error checking
data, err := readFile(path)
if err != nil { return err }
config, err := parseConfig(data)
if err != nil { return err }
validated, err := validate(config)
if err != nil { return err }
```

With Result and `mo.Do`, errors short-circuit through the chain:

```go
// With mo — errors propagate automatically via Do notation
result := mo.Do(func() Config {
    data := mo.TupleToResult(readFile(path)).MustGet()
    config := mo.TupleToResult(parseConfig(data)).MustGet()
    validated := mo.TupleT

Sponsored

Ads related to golang-samber-mo and adjacent AI workflows.