package main
import (
"errors"
"fmt"
"strconv"
)
type Result[T any] struct {
Value T
Err error
}
func Ok[T any](v T) Result[T] { return Result[T]{Value: v} }
func Err[T any](e error) Result[T] { var z T; return Result[T]{Value: z, Err: e} }
func (r Result[T]) Unwrap() (T, error) { return r.Value, r.Err }
// Chainable: only run f if no prior error
func Map[T, U any](r Result[T], f func(T) U) Result[U] {
if r.Err != nil { return Err[U](r.Err) }
return Ok(f(r.Value))
}
func parseAndDouble(s string) Result[int] {
n, err := strconv.Atoi(s)
if err != nil { return Err[int](err) }
return Ok(n * 2)
}
func main() {
fmt.Println(parseAndDouble("21")) // {42 <nil>}
fmt.Println(parseAndDouble("xyz")) // {0 strconv.Atoi: parsing ...}
chained := Map(parseAndDouble("10"), func(n int) string {
return fmt.Sprintf("got %d", n)
})
fmt.Println(chained) // {got 20 <nil>}
_ = errors.New // (silence import)
}
Create a free account and build your private vault. Share publicly whenever you want.