go-samber-mo
Monadic types for Go with samber/mo. Covers Option, Result, Either, and functional composition patterns.
SKILL.mdskills/go/go-samber-mo/SKILL.md
GitHubCore Philosophy
samber/mo brings functional programming safety to Go by providing Monads. These types help make impossible states (like nil pointer dereferences) unrepresentable at the type level.
- Option[T]: Represents a value that may be present (
Some) or absent (None). Replaces the need fornilpointers. - Result[T]: Represents a successful result (
Ok) or a failure (Err). Replaces the(T, error)pattern with a single value. - Either[L, R]: Represents a value that is either type
L(Left) or typeR(Right). Useful for alternative paths.
Key Types and Usage
Option[T]
// Create
opt := mo.Some("Alice")
none := mo.None[string]()
// Use
name := opt.OrElse("Guest") // "Alice"
empty := none.OrElse("Guest") // "Guest"
// Map (transform)
upper := opt.Map(func(s string) (string, bool) {
return strings.ToUpper(s), true
})
Result[T]
// Create
res := mo.Ok(42)
err := mo.Err[int](fmt.Errorf("failed"))
// Wrap existing Go calls
res := mo.TupleToResult(os.ReadFile("config.yaml"))
// Use
data := res.OrElse([]byte("{}"))
Either[L, R]
// Create
left := mo.Left[int, string](404)
right := mo.Right[int, string]("Not Found")
// Match
msg := left.Match(
func(code int) string { return fmt.Sprintf("Error: %d", code) },
func(s string) string { return s },
)
Why use Monads?
- Nil Safety:
Optionforces you to handle theNonecase explicitly, preventing nil pointer panics. - Composability: You can chain operations (Map, FlatMap) without writing repeated
if err != nilchecks. - Clarity: The return type clearly signals that a value might be missing or an operation might fail.
- JSON/DB Support:
OptionandResultimplement standard interfaces for JSON marshaling and SQL scanning.
Best Practices
- Prefer
OrElseoverMustGet—MustGetwill panic if the value is missing. Use it only when you are absolutely sure or inside a recovery block. - Use
DoNotation — For complex chains of operations that might fail, usemo.Doto write imperative-style code that is automatically wrapped in aResult. - Accept Monads, Return Monads — Use these types in your internal service boundaries to propagate safety throughout your application.
Anti-patterns
- ❌ Mixing Monads and
nil— Don't return*Option[T]. TheOptionitself is the safety wrapper. - ❌ Over-nesting — Chaining too many
FlatMapcalls can become hard to follow. Use intermediate variables ormo.Do. - ❌ Ignoring
ErrinResult— Always handle the error case viaOrElse,Match, or by returning theResultto the caller. - ❌ Using
Optionfor everything — If a value is logically always required, use a plain type. Only useOptionfor truly optional fields.