复制安装命令
用 Codex 或 Claude 安装复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它先审查 Skill 页面再帮你安装。
复制前请先查看来源、License 和安全提示。
AI agent skills are reusable instruction sets that extend your coding assistant with domain-spec...
用 Codex 或 Claude 安装复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它先审查 Skill 页面再帮你安装。
复制前请先查看来源、License 和安全提示。
来源文件:README.md
AI agent skills are reusable instruction sets that extend your coding assistant with domain-specific expertise, loaded on demand so they don't bloat your context. This repository covers Go-specific skills only (language, testing, security, observability, etc.); for dev workflow skills (git conventions, CI/CD, PR reviews) you'll want to add a separate skills plugin.
For generic skills, please visit cc-skills.
[!IMPORTANT] Bootstrapped with Claude Code by distilling my Go project commits. Edited, tested, reviewed and reworked by a human.
No AI slop here. AI-made skills are useless.
Install with skills CLI (universal, works with any Agent Skills-compatible tool):
npx skills add https://github.com/samber/cc-skills-golang --all
# or a single skill:
npx skills add https://github.com/samber/cc-skills-golang --skill golang-performance
/plugin marketplace add samber/cc
/plugin install cc-skills-golang@samber
Copy skills into the cross-client discovery directory:
git clone https://github.com/samber/cc-skills-golang.git ~/.openclaw/skills/cc-skills-golang
# or in workspace:
git clone https://github.com/samber/cc-skills-golang.git ~/.openclaw/workspace/skills/cc-skills-golang
gemini extensions install https://github.com/samber/cc-skills-golang
Update with gemini extensions update cc-skills-golang.
Copy skills into the cross-client discovery directory:
git clone https://github.com/samber/cc-skills-golang.git ~/.cursor/skills/cc-skills-golang
Cursor auto-discovers skills from .agents/skills/ and .cursor/skills/.
Copy skills into the cross-client discovery directory:
/plugin install https://github.com/samber/cc-skills-golang
# or
git clone https://github.com/samber/cc-skills-golang.git ~/.copilot/skills/cc-skills-golang
Copilot auto-discovers skills from .copilot/skills/.
Copy skills into the cross-client discovery directory:
git clone https://github.com/samber/cc-skills-golang.git ~/.agents/skills/cc-skills-golang
OpenCode auto-discovers skills from .agents/skills/, .opencode/skills/, and .claude/skills/.
Clone into the cross-client discovery path:
git clone https://github.com/samber/cc-skills-golang.git ~/.agents/skills/cc-skills-golang
Codex auto-discovers skills from ~/.agents/skills/ and .agents/skills/. Update with cd ~/.agents/skills/cc-skills-golang && git pull.
Clone and symlink into the cross-client discovery path:
git clone https://github.com/samber/cc-skills-golang.git ~/.antigravity/skills/cc-skills-golang
Update with cd ~/.antigravity/skills/cc-skills-golang && git pull.
These skills are designed as atomic, cross-referencing units. A skill may reference conventions defined in another (e.g. error-handling rules that affect logging live in golang-error-handling, not golang-observability). Installing only a subset will give you a partial and potentially inconsistent view of the guidelines. For best results, install all general-purpose skills together.
┌────────────────────────────────────────┐
│ Golang Skills │
└──────────────────┬─────────────────────┘
│
┌─────────────────┬──────────────────────┼──────────────────────┐
▼ ▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌─────────────────┐ ┌──────────────────────┐
│ Code Quality │ │ Arch & Design│ │ QA & Perf │ │ Project Start │
├──────────────┤ ├──────────────┤ ├─────────────────┤ ├──────────────────────┤
│ code-style │ │ design-patt │ │ testing │ │ project-layout │
│ naming │ │ concurrency │ │ benchmark │ │ popular-libs │
│ error-handl │ │ context │ │ performance │ │ cli │
│ safety │ │ dep-inject │ │ troubleshoot │ │ continuous-integ. │
│ structs-iface│ │ data-structs │ │ observability │ │ stay-updated │
│ documentation│ │ database │ │ │ │ dep-management │
│ lint │ │ modernize │ │ │ │ gopls │
│ security │ │ refactoring │ │ │ │ pkg-go-dev │
└──────────────┘ └──────────────┘ └─────────────────┘ └──────────────────────┘
┌─────────────────────────────────────────────────────────────────────────┐
│ Framework / Library Skills │
├──────────────┬────────────────┬──────────────┬─────────────┬───────────┤
│ APIs │ DI │ Frameworks │ samber/* │ Testing │
├──────────────┼────────────────┼──────────────┼─────────────┼───────────┤
│ grpc │ google-wire │ spf13-cobra │ samber-lo │ stretchr- │
│ graphql │ uber-dig │ spf13-viper │ samber-mo │ testify │
│ swagger │ uber-fx │ │ samber-ro │ │
│ │ │ │ samber-do │ │
│ │ │ │ samber-hot │ │
│ │ │ │ samber-slog │ │
│ │ │ │ samber-oops │ │
└──────────────┴────────────────┴──────────────┴─────────────┴───────────┘
description field from YAML frontmatter, always loaded into Claude's context for skill triggeringSKILL.md file loaded when the skill triggersGeneral purpose:
| Skill | Flags | Error rate gap | Description (tok) | SKILL.md (tok) | Directory (tok) | |
|---|---|---|---|---|---|---|
| ⭐️ | ✅ golang-code-style | ⚡ 🤖 ⚙️ | -40% | 115 | 2,341 | 2,957 |
| ⭐️ | ✅ golang-data-structures | ⚡ | -39% | 93 | 2,599 | 6,318 |
| ⭐️ | ✅ golang-database | ⚡ ⚙️ | -38% | 97 | 2,712 | 7,234 |
| ⭐️ | ✅ golang-design-patterns | ⚡ ⚙️ | -37% | 80 | 2,685 | 9,391 |
| ⭐️ | ✅ golang-documentation | ⚡ 🤖 ⚙️ | -53% | 75 | 3,078 | 11,177 |
| ⭐️ | ✅ golang-error-handling | ⚡ 🤖 ⚙️ | -26% | 141 | 1,718 | 4,677 |
| ⭐️ | ✅ golang-how-to | ⚡ | — | 165 | 4,017 | 13,853 |
| ⭐️ | ✅ golang-modernize | ⚡ 🤖 | -61% | 68 | 2,920 | 9,233 |
| ⭐️ | ✅ golang-naming | ⚡ ⚙️ | -23% | 159 | 3,022 | 7,390 |
| ⭐️ | ✅ golang-refactoring | ⚡ 🧠 🤖 ⚙️ | — | 246 | 3,708 | 20,216 |
| ⭐️ | ✅ golang-safety | ⚡ | -58% | 78 | 2,605 | 5,375 |
| ⭐️ | ✅ golang-testing | ⚡ 🧠 🤖 ⚙️ | -32% | 115 | 4,234 | 7,341 |
| ⭐️ | ✅ golang-troubleshooting | ⚡ 🧠 🤖 | -32% | 128 | 2,894 | 16,577 |
| ⭐️ | ✅ golang-security | ⚡ 🧠 🤖 | -32% | 85 | 3,160 | 21,596 |
✅ golang-benchmark | ⚡ 🧠 | -50% | 102 | 3,042 | 30,224 | |
✅ golang-cli | ⚡ | -43% | 125 | 2,329 | 6,144 | |
✅ golang-concurrency | ⚡ 🤖 ⚙️ | -39% | 72 | 2,180 | 6,810 | |
✅ golang-context | ⚡ ⚙️ | -34% | 82 | 1,202 | 4,012 | |
✅ golang-continuous-integration | ⚡ | -59% | 82 | 3,291 | 12,553 | |
✅ golang-dependency-injection | ⚡ 🤖 ⚙️ | -47% | 178 | 2,994 | 5,265 | |
✅ golang-dependency-management | ⚡ | -54% | 77 | 2,361 | 5,499 | |
✅ golang-structs-interfaces | ⚡ ⚙️ | -35% | 111 | 3,067 | 3,067 | |
✅ golang-lint | ⚡ 🤖 | -41% | 98 | 1,853 | 6,181 | |
✅ golang-observability | ⚡ 🤖 ⚙️ | -37% | 164 | 3,096 | 18,583 | |
✅ golang-performance | ⚡ 🧠 🤖 | -39% | 130 | 2,190 | 18,190 | |
✅ golang-gopls | ⚡ | — | 219 | 2,308 | 12,188 | |
✅ golang-pkg-go-dev | ⚡ | — | 230 | 3,428 | 5,242 | |
✅ golang-popular-libraries | ⚡ | -30% | 51 | 1,044 | 4,438 | |
✅ golang-project-layout | ⚡ | -38% | 69 | 1,563 | 5,778 | |
✅ golang-stay-updated | ⚡ | -56% | 44 | 1,801 | 1,801 |
Tools:
| Skill | Flags | Error rate gap | Description (tok) | SKILL.md (tok) | Directory (tok) |
|---|---|---|---|---|---|
✅ golang-google-wire | ⚡ | -16% | 122 | 2,661 | 7,391 |
✅ golang-graphql | -16% | 76 | 3,061 | 7,932 | |
✅ golang-grpc | ⚡ | -41% | 70 | 2,332 | 5,148 |
✅ golang-spf13-cobra | ⚡ | — | 176 | 2,571 | 7,342 |
✅ golang-spf13-viper | ⚡ | — | 170 | 2,542 | 7,089 |
✅ golang-swagger | ⚡ | — | 144 | 2,333 | 3,338 |
✅ golang-uber-dig | ⚡ | -10% | 107 | 2,576 | 6,248 |
✅ golang-uber-fx | ⚡ | -5% | 118 | 2,816 | 7,051 |
✅ golang-samber-do | ⚡ | -81% | 71 | 1,877 | 3,392 |
✅ golang-samber-hot | ⚡ | -54% | 119 | 1,977 | 7,407 |
✅ golang-samber-lo | ⚡ | -40% | 167 | 2,601 | 10,279 |
✅ golang-samber-mo | ⚡ 🧠 | -48% | 82 | 2,943 | 11,358 |
✅ golang-samber-oops | ⚡ | -59% | 70 | 2,535 | 2,847 |
✅ golang-samber-ro | ⚡ 🧠 | -50% | 154 | 2,952 | 11,168 |
✅ golang-samber-slog | ⚡ | -19% | 119 | 3,111 | 9,833 |
❌ golang-temporal | — | 0 | 0 | 0 | |
✅ golang-stretchr-testify | ⚡ | -47% | 92 | 1,849 | 2,668 |
| With Skill | Without Skill | Delta | |
|---|---|---|---|
| Overall | 3315/3395 (98%) | 1915/3395 (56%) | +41pp |
See EVALUATIONS.md for the full per-skill breakdown.
golang-code-styleGo code formatting and conventions. gofmt, goimports, linting rules, comment conventions, and project-level style consistency. Overridable by company skills.
golang-documentationGo documentation standards. Package docs, godoc conventions, code comments, example functions, README structure, and API reference generation. Overridable.
golang-error-handlingGo error handling best practices. Error creation, wrapping with fmt.Errorf and errors.Is/As, sentinel errors, custom error types, error codes, and panic recovery. Overridable.
golang-lintGo linting best practices and golangci-lint configuration. Presets, custom rules, CI integration, inline suppression, and output interpretation.
golang-namingGo naming conventions across all identifier types. Packages, constructors, structs, interfaces, constants, errors, receivers, acronyms, test functions. Covers MixedCaps rules, Get-prefix, and utils/helpers anti-patterns. Overridable.
golang-safetyDefensive Go coding. Prevents panics, silent data corruption, and runtime bugs. nil safety, append aliasing, map concurrent access, float comparison, zero-value design, numeric overflow.
golang-securityGo security best practices. Injection prevention (SQL, command, XSS), cryptography, filesystem/network safety, secrets management, cookie security, and tool configuration. Audit and review modes.
golang-structs-interfacesGo struct and interface design. Composition, embedding, type assertions, interface segregation, struct tags (JSON/YAML/DB), pointer vs value receivers. Overridable.
golang-concurrencyGo concurrency patterns. Goroutines, channels, sync primitives, context cancellation, worker pools, fan-out/fan-in, pipelines. Overridable.
golang-contextIdiomatic context.Context usage. Creation, cancellation, timeouts, values, propagation patterns, and common anti-patterns. Overridable.
golang-data-structuresGo data structures internals and usage. Slices (capacity growth, append aliasing), maps, channels, sync primitives, and when to use each.
golang-databaseGo database access patterns. Parameter binding, connection pooling, transactions, migrations, sqlboiler/sqlc code generation, query builders. Overridable.
golang-dependency-injectionDependency injection patterns in Go. Constructor injection, interface-based DI, wire/dig/fx comparison, and when DI is worth the complexity. Overridable.
golang-design-patternsIdiomatic Go design patterns. Functional options, constructors, builder pattern, middleware chains, circuit breaker, and architecture guides with file trees and code. Overridable.
golang-modernizeModernize Go code to use recent language features. Range-over-int, min/max builtins, iterators, slices/maps/cmp/slog stdlib packages, testing patterns (t.Context, b.Loop, synctest), and tooling upgrades.
golang-refactoringSafe, at-scale refactoring process for existing Go code. Coverage-adaptive safety net, tool-driven behavior-preserving transforms (gopls Rename/Inline/Extract, gofmt -r, eg, gopatch), the Fowler catalog mapped to Go, breaking import cycles, type-alias gradual code repair, and a human-in-the-loop workflow of staged PRs on a refactoring branch.
golang-benchmarkGo benchmarking, profiling, and performance measurement. pprof, trace, CPU/memory/block profiles, flame graphs, benchmark comparison (benchstat), continuous profiling.
golang-observabilityGo production observability. Structured logging (slog), Prometheus metrics, OpenTelemetry tracing, pprof profiling, RUM tracking, alerting, Grafana dashboards. Overridable.
golang-performanceGo performance optimization. Allocation reduction, CPU efficiency, memory layout, GC tuning, pooling, caching, hot-path optimization. Review and hot-path modes.
golang-testingProduction-ready Go tests. Table-driven tests, fuzzing, fixtures, goroutine leak detection (goleak), snapshot testing, code coverage, integration tests, parallel tests. Overridable.
golang-troubleshootingSystematic Go debugging methodology. Common pitfalls, test-driven debugging, pprof capture, Delve debugger, race detection, GODEBUG tracing, production debugging.
golang-cliGo CLI application development. Project layout, exit codes, signal handling, I/O patterns, argument parsing, and terminal UX.
golang-continuous-integrationCI/CD pipeline configuration for Go projects using GitHub Actions. Build, test, lint, and release workflows.
golang-dependency-managementGo module dependency strategies. go.mod conventions, versioning, replace directives, tool dependencies, and multi-module workspaces.
golang-goplsSemantic code intelligence for your local build via gopls, the official Go language server. Go-to-definition, find references, call/implementation hierarchy, workspace symbol search, diagnostics, safe rename, and refactors (extract/inline/fill/rewrite). Reachable via gopls's own MCP server, Claude Code's native LSP tool, or the gopls CLI.
golang-pkg-go-devGo package and module exploration via godig, a pkg.go.dev API client (CLI + MCP server). Package docs, API references, symbols, code examples, versions, importers, licenses, and known vulnerabilities. Prefer over Context7 for Go packages.
golang-popular-librariesCurated recommendations for production-ready Go libraries and frameworks. When the stdlib is enough vs when to reach for a package.
golang-project-layoutGo project structure and workspace setup. cmd/internal/pkg conventions, monorepo layout, CLI project structure, and when to keep things flat.
golang-stay-updatedResources to stay current with Go. Official channels, community hubs, key people to follow, and learning resources.
golang-graphqlGraphQL API development in Go using gqlgen/graphql-go. Schema definition, resolvers, subscriptions, dataloader, and federation.
golang-grpcgRPC in Go. Protobuf organization, service definitions, streaming, interceptors, error codes, and code generation workflow.
golang-swaggerOpenAPI/Swagger docs with swaggo/swag. Annotation comments, code generation, framework integrations (gin, echo, fiber, chi), security definitions.
golang-google-wireCompile-time dependency injection with google/wire. Provider sets, injector generation, wire.Build, and structured DI patterns.
golang-uber-digReflection-based DI with uber-go/dig. Provide/Invoke, dig.In/dig.Out, named values, value groups, optional dependencies, and Decorate.
golang-uber-fxApplication framework with uber-go/fx. fx.New, fx.Provide/Invoke, fx.Module, lifecycle hooks, fx.Annotate, fx.Decorate, signal-aware Run.
golang-spf13-cobraCLI command trees with spf13/cobra. Command hierarchy, RunE hooks, flag management, shell completion, usage templates, and testing with SetArgs.
golang-spf13-viperLayered configuration with spf13/viper. Flag > env > file > KV > default precedence, BindPFlag, hot reload, test isolation, and remote KV integration.
golang-samber-doDependency injection with samber/do. Type-safe service containers, lifecycle management, scopes, health checks, and graceful shutdown.
golang-samber-hotIn-memory caching with samber/hot. 9 eviction algorithms (LRU, LFU, TinyLFU, W-TinyLFU, S3FIFO, ARC, SIEVE...), TTL, loaders, sharding, stale-while-revalidate, Prometheus metrics.
golang-samber-loFunctional programming helpers with samber/lo. 500+ type-safe generic functions for slices, maps, channels, strings. Immutable (lo), parallel (lop), mutable (lom), iterators (loi), SIMD.
golang-samber-moMonadic types with samber/mo. Option, Result, Either, Future, IO, Task, State for type-safe nullable values, error handling, and functional composition.
golang-samber-oopsStructured error handling with samber/oops. Error builders, stack traces, error codes, context attributes, public vs developer messages, panic recovery, and APM integration.
golang-samber-roReactive streams with samber/ro. 150+ type-safe operators, cold/hot observables, 5 subject types, 40+ plugins, automatic backpressure, and Go context integration.
golang-samber-slogStructured logging pipeline with samber/slog-**** packages. Multi-handler routing (slog-multi), sampling, formatting, HTTP middleware, and 20+ backend sinks.
golang-stretchr-testifyTesting with stretchr/testify. assert, require, mock, and suite packages. Assertions, mock expectations, argument matchers, suite lifecycle, and custom matchers.
Add AI agents as PR reviewers alongside traditional static analysis. When configured with this skill plugin, the agent applies the relevant Go skills per review area — catching architectural drift, logic bugs, and concurrency hazards that linters cannot detect.
See GOLANG-AI-DRIVEN-REVIEW.md for full setup instructions (Claude Code Action and GitHub Copilot).
If a skill triggers too often or not often enough, please open an issue suggesting a description change. The description field in SKILL.md frontmatter is the primary triggering mechanism — small wording adjustments can significantly improve trigger accuracy. Some SKILL.md files might have a When to use section which is another level of exclusion. Finally, SKILL.md files are an entrypoint for lazy loading references with deep knowledge located in references/.
Claude reports very little overlap between skills in this repo, thanks to cross-reference. I suggest enabling most of the skills and leveraging lazy loading. The recommended ⭐️ skills load ~1,100 tokens of descriptions at startup; full skill content is only pulled in when relevant. Note:
golang-naming and golang-code-style overlap with linters (golangci-lint).golang-security have been distilled from the Bearer (SAST) checklist. The skill is still useful for methodology.This skill supersedes samber/cc-skills-golang@golang-naming skill for [company] projects. Skills marked ⚙️ in the table above support this mechanism.[Logging](./logging.md)). Claude reads these on demand when the topic is relevant, so they don't count against the context budget until neededFor more guidelines, please check CLAUDE.md.
Copyright © 2026 Samuel Berthe.
This project is under MIT license.
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 or similar AI coding agents, and for projects using Golang.
metadata:
author: samber
version: "1.0.7"
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__*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: Use ultrathink when designing multi-step Option/Result/Either pipelines. Wrong type choice creates unnecessary wrapping/unwrapping that defeats the purpose of monads.
Go 1.18+ library providing type-safe monadic types with zero dependencies. Inspired by Scala, Rust, and fp-ts.
Official Resources:
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.
go get github.com/samber/mo
For an introduction to functional programming concepts and why monads are valuable in Go, see Monads Guide.
| 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 |
Future[T] | Async value not yet available | JavaScript Promise |
IO[T] | Lazy synchronous side effect | Haskell's IO |
Task[T] | Lazy async computation | fp-ts Task |
State[S, A] | Stateful computation | Haskell's State monad |
Represents a value that is either present (Some) or absent (None). Eliminates nil pointer risks at the type level.
import "github.com/samber/mo"
name := mo.Some("Alice") // Option[string] with value
empty := mo.None[string]() // Option[string] without value
fromPtr := mo.PointerToOption(ptr) // nil pointer -> None
// Safe extraction
name.OrElse("Anonymous") // "Alice"
empty.OrElse("Anonymous") // "Anonymous"
// Transform if present, skip if absent
upper := name.Map(func(s string) (string, bool) {
return strings.ToUpper(s), true
})
Key methods: Some, None, Get, MustGet, OrElse, OrEmpty, Map, FlatMap, Match, ForEach, ToPointer, IsPresent, IsAbsent.
Option implements json.Marshaler/Unmarshaler, sql.Scanner, driver.Valuer — use it directly in JSON structs and database models.
For full API reference, see Option Reference.
Represents success (Ok) or failure (Err). Equivalent to Either[error, T] but specialized for Go's error pattern.
// Wrap Go's (value, error) pattern
result := mo.TupleToResult(os.ReadFile("config.yaml"))
// Same-type transform — errors short-circuit automatically
upper := mo.Ok("hello").Map(func(s string) (string, error) {
return strings.ToUpper(s), nil
})
// Ok("HELLO")
// Extract with fallback
val := upper.OrElse("default")
Go limitation: Direct methods (.Map, .FlatMap) cannot change the type parameter — Result[T].Map returns Result[T], not Result[U]. Go methods cannot introduce new type parameters. For type-changing transforms (e.g. Result[[]byte] to Result[Config]), use sub-package functions or mo.Do:
import "github.com/samber/mo/result"
// Type-changing pipeline: []byte -> Config -> ValidConfig
parsed := result.Pipe2(
mo.TupleToResult(os.ReadFile("config.yaml")),
result.Map(func(data []byte) Config { return parseConfig(data) }),
result.FlatMap(func(cfg Config) mo.Result[ValidConfig] { return validate(cfg) }),
)
Key methods: Ok, Err, Errf, TupleToResult, Try, Get, MustGet, OrElse, Map, FlatMap, MapErr, Match, ForEach, ToEither, IsOk, IsError.
For full API reference, see Result Reference.
Represents a value that is one of two possible types. Unlike Result, neither side implies success or failure — both are valid alternatives.
// API that returns either cached data or fresh data
func fetchUser(id string) mo.Either[CachedUser, FreshUser] {
if cached, ok := cache.Get(id); ok {
return mo.Left[CachedUser, FreshUser](cached)
}
return mo.Right[CachedUser, FreshUser](db.Fetch(id))
}
// Pattern match
result := fetchUser("user-123")
result.Match(
func(cached CachedUser) mo.Either[CachedUser, FreshUser] { /* use cached */ },
func(fresh FreshUser) mo.Either[CachedUser, FreshUser] { /* use fresh */ },
)
When to use Either vs Result: Use Result[T] when one path is an error. Use Either[L, R] when both paths are valid alternatives (cached vs fresh, left vs right, strategy A vs B).
Either3[T1, T2, T3], Either4, and Either5 extend this to 3-5 type variants.
For full API reference, see Either Reference.
mo.Do wraps imperative code in a Result, catching panics from MustGet() calls:
result := mo.Do(func() int {
// MustGet panics on None/Err — Do catches it as Result error
a := mo.Some(21).MustGet()
b := mo.Ok(2).MustGet()
return a * b // 42
})
// result is Ok(42)
result := mo.Do(func() int {
val := mo.None[int]().MustGet() // panics
return val
})
// result is Err("no such element")
Do notation bridges imperative Go style with monadic safety — write straight-line code, get automatic error propagation.
samber/mo provides two ways to compose operations:
Direct methods (.Map, .FlatMap) — work when the output type equals the input type:
opt := mo.Some(42)
doubled := opt.Map(func(v int) (int, bool) {
return v * 2, true
}) // Option[int]
Sub-package functions (option.Map, result.Map) — required when the output type differs from input:
import "github.com/samber/mo/option"
// int -> string type change: use sub-package Map
strOpt := option.Map(func(v int) string {
return fmt.Sprintf("value: %d", v)
})(mo.Some(42)) // Option[string]
Pipe functions (option.Pipe3, result.Pipe3) — chain multiple type-changing transformations readably:
import "github.com/samber/mo/option"
result := option.Pipe3(
mo.Some(42),
option.Map(func(v int) string { return strconv.Itoa(v) }),
option.Map(func(s string) []byte { return []byte(s) }),
option.FlatMap(func(b []byte) mo.Option[string] {
if len(b) > 0 { return mo.Some(string(b)) }
return mo.None[string]()
}),
)
Rule of thumb: Use direct methods for same-type transforms. Use sub-package functions + pipes when types change across steps.
For detailed pipeline API reference, see Pipelines Reference.
type UserResponse struct {
Name string `json:"name"`
Nickname mo.Option[string] `json:"nickname"` // omits null gracefully
Bio mo.Option[string] `json:"bio"`
}
type User struct {
ID int
Email string
Phone mo.Option[string] // implements sql.Scanner + driver.Valuer
}
err := row.Scan(&u.ID, &u.Email, &u.Phone)
// Convert map lookup to Option
func MapGet[K comparable, V any](m map[K]V, key K) mo.Option[V] {
return mo.TupleToOption(m[key]) // m[key] returns (V, bool)
}
mo.Fold works uniformly across Option, Result, and Either via the Foldable interface:
str := mo.Fold[error, int, string](
mo.Ok(42), // works with Option, Result, or Either
func(v int) string { return fmt.Sprintf("got %d", v) },
func(err error) string { return "failed" },
)
// "got 42"
OrElse over MustGet — MustGet panics on absent/error values; use it only inside mo.Do blocks where panics are caught, or when you are certain the value existsTupleToResult at API boundaries — convert Go's (T, error) to Result[T] at the boundary, then chain with Map/FlatMap inside your domain logicResult[T] for errors, Either[L, R] for alternatives — Result is specialized for success/failure; Either is for two valid typesOption[string] distinguishes "absent" from "empty string"; use plain string when empty string is a valid valueresult.Map(...).FlatMap(...).OrElse(default) reads left-to-right; avoid nested if/else patterns when monadic chaining is cleaneroption.Pipe3(...) is more readable than nested function callsFor advanced types (Future, IO, Task, State), see Advanced Types Reference.
If you encounter a bug or unexpected behavior in samber/mo, open an issue at https://github.com/samber/mo/issues.
samber/cc-skills-golang@golang-samber-lo skill for functional collection transforms (Map, Filter, Reduce on slices) that compose with mo typessamber/cc-skills-golang@golang-error-handling skill for idiomatic Go error handling patternssamber/cc-skills-golang@golang-safety skill for nil-safety and defensive Go codingsamber/cc-skills-golang@golang-database skill for database access patternssamber/cc-skills-golang@golang-design-patterns skill for functional options and other Go patterns
评论 (0)
暂无评论,成为第一个评论者吧!