Go

Generic Result / Option Type

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Go doesn't have built-in Result types, but generics make them ergonomic. Combine with `errors.Is` and you have type-safe railroaded error handling.
Go
Raw
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)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.