A Rust-inspired Result type for Go, enabling elegant error handling with generics.
- Generic Result type supporting any value and error types
- Chainable operations for cleaner error handling
- Panic-free error propagation
- Fully tested and production-ready
go get github.com/osesantos/resultopackage main
import (
"errors"
"fmt"
"github.com/osesantos/resulto"
)
func divide(a, b int) resulto.Result[int] {
if b == 0 {
return resulto.Failure[int](errors.New("division by zero"))
}
return resulto.Success(a / b)
}
func main() {
// Successful result
result1 := divide(10, 2)
if result1.IsOk() {
fmt.Printf("Result: %d\n", result1.Unwrap())
}
// Failed result with safe unwrap
result2 := divide(5, 0)
value := result2.UnwrapOr(0)
fmt.Printf("Safe value: %d\n", value)
}package main
import (
"errors"
"fmt"
"github.com/osesantos/resulto"
"strconv"
)
func parseAndDouble(input string) resulto.Result[int] {
return parseString(input).Map(func(n int) int {
return n * 2
})
}
func parseString(input string) resulto.Result[int] {
n, err := strconv.Atoi(input)
if err != nil {
return resulto.Failure[int](err)
}
return resulto.Success(n)
}
func main() {
// Chaining operations
parseAndDouble("5").Match(
func(n int) { fmt.Printf("Doubled: %d\n", n) },
func(err error) { fmt.Printf("Error: %s\n", err.Error()) },
)
// Error handling
parseAndDouble("invalid").Match(
func(n int) { fmt.Printf("Doubled: %d\n", n) },
func(err error) { fmt.Printf("Error: %s\n", err.Error()) },
)
}Success[T](value T) Result[T]: Create a successful resultFailure[T](err error) Result[T]: Create a failed result
IsOk() bool: Check if result is successfulUnwrap() T: Get value or panic if errorUnwrapOr(def T) T: Get value or default if errorUnwrapErr() error: Get error or panic if successful
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.