Documentation
¶
Overview ¶
Package fp provides functional programming primitives for Go. It implements monadic types like Option and Result for more expressive error handling.
Package fp provides functional programming primitives for Go.
Index ¶
- Variables
- type Option
- func (o Option[T]) IsNone() bool
- func (o Option[T]) IsSome() bool
- func (o Option[T]) Map(fn func(T) T) Option[T]
- func (o Option[T]) MapOr(value T, fn func(T) T) T
- func (o Option[T]) MapOrElse(handleNone func() T, handleSome func(T) T) T
- func (o Option[T]) MarshalJSON() ([]byte, error)
- func (o Option[T]) Match(handleSome func(T) T, handleNone func() T) T
- func (o Option[T]) MatchAny(whenSome, whenNone any) any
- func (o Option[T]) OkOr(err error) Result[T]
- func (o Option[T]) OkOrElse(fn func() error) Result[T]
- func (o Option[T]) Or(other Option[T]) Option[T]
- func (o Option[T]) OrElse(fn func() Option[T]) Option[T]
- func (o *Option[T]) UnmarshalJSON(data []byte) error
- func (o Option[T]) Unwrap() (T, bool)
- func (o Option[T]) UnwrapOr(value T) T
- func (o Option[T]) UnwrapOrDefault() T
- func (o Option[T]) UnwrapOrElse(fn func() T) T
- func (o Option[T]) UnwrapUnsafe() T
- type Result
- func (r Result[T]) And(other Result[T]) Result[T]
- func (r Result[T]) AndThen(fn func() T) Result[T]
- func (r Result[T]) IsErr() bool
- func (r Result[T]) IsOk() bool
- func (r Result[T]) Map(fn func(T) T) Result[T]
- func (r Result[T]) MapOr(value T, fn func(T) T) Result[T]
- func (r Result[T]) MapOrElse(handleErr func(error) T, handleOk func(T) T) Result[T]
- func (r Result[T]) Match(handleOk func(T) Result[T], handleErr func(error) Result[T]) Result[T]
- func (r Result[T]) Or(other Result[T]) Result[T]
- func (r Result[T]) OrElse(fn func() Result[T]) Result[T]
- func (r Result[T]) Unwrap() (T, error)
- func (r Result[T]) UnwrapOr(other T) T
- func (r Result[T]) UnwrapOrDefault() T
- func (r Result[T]) UnwrapOrElse(fn func() T) T
- func (r Result[T]) UnwrapUnsafe() T
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // OkAny is a predefined Result with a nil error and a zero any value. // Useful as a placeholder when only the success/failure state matters. OkAny = Result[any]{} )
Functions ¶
This section is empty.
Types ¶
type Option ¶
type Option[T any] struct { // contains filtered or unexported fields }
Option represents an optional value: either Some value or None. It's a type that encapsulates an optional value, avoiding the need for nil checks.
Example ¶
ExampleOption demonstrates basic usage of the Option type.
// Create Some and None options
someValue := Some(42)
noneValue := None[int]()
// Check if options have values
fmt.Printf("Some has value: %v\n", someValue.IsSome())
fmt.Printf("None has value: %v\n", noneValue.IsSome())
// Extract values safely
if value, ok := someValue.Unwrap(); ok {
fmt.Printf("Value: %d\n", value)
}
Output: Some has value: true None has value: false Value: 42
func None ¶
None creates a new Option in the None state. This is a constructor function for creating an Option that does not contain a value.
Example ¶
ExampleNone demonstrates creating an empty Option.
// Create an empty Option
empty := None[string]()
fmt.Printf("Has value: %t\n", empty.IsSome())
fmt.Printf("Value: %s\n", empty.UnwrapOr("default"))
Output: Has value: false Value: default
func OptionFromPtr ¶
OptionFromPtr creates an Option from a pointer. If the pointer is nil, returns None, otherwise returns Some with the dereferenced value. This is useful for converting nullable pointers to the Option type.
Example ¶
ExampleOptionFromPtr demonstrates creating Option from a pointer.
// From valid pointer
value := "hello"
opt1 := OptionFromPtr(&value)
// From nil pointer
var nilPtr *string
opt2 := OptionFromPtr(nilPtr)
fmt.Printf("From pointer: %s\n", opt1.UnwrapOr("empty"))
fmt.Printf("From nil: %s\n", opt2.UnwrapOr("empty"))
Output: From pointer: hello From nil: empty
func OptionFromTuple ¶
OptionFromTuple creates an Option from a tuple-like return (value, ok). If ok is true, returns Some(x), otherwise returns None. This is useful for converting Go's common (value, ok) pattern to an Option.
Example ¶
ExampleOptionFromTuple demonstrates creating Option from a tuple pattern.
// Common Go pattern: value, ok
getValue := func(key string) (string, bool) {
data := map[string]string{"name": "Alice", "age": "25"}
value, ok := data[key]
return value, ok
}
// Convert to Option
nameOpt := OptionFromTuple(getValue("name"))
missingOpt := OptionFromTuple(getValue("missing"))
fmt.Printf("Name: %s\n", nameOpt.UnwrapOr("unknown"))
fmt.Printf("Missing: %s\n", missingOpt.UnwrapOr("unknown"))
Output: Name: Alice Missing: unknown
func OptionFromTupleErr ¶ added in v0.10.0
func OptionFromZero ¶
func OptionFromZero[T comparable](x T) Option[T]
OptionFromZero creates an Option from a value, treating zero values as None. If the value equals the zero value for its type, returns None, otherwise returns Some(x). This is useful when zero values are treated as invalid or unset.
func Some ¶
Some creates a new Option in the Some state with the given value. This is a constructor function for creating an Option that contains a value.
Example ¶
ExampleSome demonstrates creating an Option with a value.
// Create an Option containing a string
message := Some("Hello, World!")
fmt.Printf("Has value: %t\n", message.IsSome())
fmt.Printf("Value: %s\n", message.UnwrapOr("default"))
Output: Has value: true Value: Hello, World!
func (Option[T]) IsNone ¶
IsNone checks if the option is in the None state. Returns true if the option does not contain a value, false otherwise.
func (Option[T]) IsSome ¶
IsSome checks if the option is in the Some state. Returns true if the option contains a value, false otherwise.
func (Option[T]) Map ¶
Map transforms the contained value using the provided function if the option is Some. If the option is None, returns None without calling the function.
Example ¶
ExampleOption_Map demonstrates transforming values inside Option.
// Start with an optional number
maybeNumber := Some(5)
// Transform it to its square
maybeSquare := maybeNumber.Map(func(x int) int { return x * x })
// Transform None value
noneNumber := None[int]()
noneSquare := noneNumber.Map(func(x int) int { return x * x })
fmt.Printf("Square of 5: %v\n", maybeSquare.UnwrapOr(0))
fmt.Printf("Square of None: %v\n", noneSquare.UnwrapOr(-1))
Output: Square of 5: 25 Square of None: -1
func (Option[T]) MapOr ¶
func (o Option[T]) MapOr(value T, fn func(T) T) T
MapOr transforms the contained value or returns a default. If the option is Some, applies the function to the contained value, otherwise returns the provided default value.
func (Option[T]) MapOrElse ¶
func (o Option[T]) MapOrElse(handleNone func() T, handleSome func(T) T) T
MapOrElse transforms the contained value or computes a default. If the option is Some, applies handleSome to the contained value, otherwise calls handleNone to compute a default.
func (Option[T]) MarshalJSON ¶ added in v0.10.0
MarshalJSON implements json.Marshaler for Option[T]. If the option is None, it marshals to null. If the option is Some, it marshals the contained value.
func (Option[T]) Match ¶
func (o Option[T]) Match(handleSome func(T) T, handleNone func() T) T
Match allows pattern matching on the Option. If the option is Some, calls handleSome with the contained value, otherwise calls handleNone.
Example ¶
ExampleOption_Match demonstrates pattern matching with Option.
// Helper function that may return a value
getValue := func(id int) Option[string] {
if id > 0 {
return Some(fmt.Sprintf("User_%d", id))
}
return None[string]()
}
// Pattern match on the result
validUser := getValue(42)
invalidUser := getValue(-1)
result1 := validUser.Match(
func(user string) string {
return "Found: " + user
},
func() string {
return "No user found"
},
)
result2 := invalidUser.Match(
func(user string) string {
return "Found: " + user
},
func() string {
return "No user found"
},
)
fmt.Printf("Valid user: %s\n", result1)
fmt.Printf("Invalid user: %s\n", result2)
Output: Valid user: Found: User_42 Invalid user: No user found
func (Option[T]) MatchAny ¶ added in v0.10.0
MatchAny allows pattern matching on the Option with any types. If the option is Some, returns whenSome, otherwise returns whenNone.
func (Option[T]) OkOr ¶
OkOr converts an Option to a Result. If the option is Some, returns Ok with the contained value, otherwise returns Err with the provided error.
func (Option[T]) OkOrElse ¶
OkOrElse converts an Option to a Result, with a computed error. If the option is Some, returns Ok with the contained value, otherwise calls the function to create an error and returns Err with that error.
func (Option[T]) Or ¶
Or returns the option if it is Some, otherwise returns the provided option. This is useful for providing a fallback option when the current one might be None.
Example ¶
ExampleOption_Or demonstrates providing fallback values.
// Create some options
primary := None[string]()
secondary := Some("backup")
tertiary := Some("fallback")
// Chain fallbacks
result := primary.Or(secondary).Or(tertiary)
fmt.Printf("Result: %s\n", result.UnwrapOr("default"))
Output: Result: backup
func (Option[T]) OrElse ¶
OrElse returns the option if it is Some, otherwise calls the function and returns its result. This is a lazy version of Or, as the fallback option is only computed if needed.
func (*Option[T]) UnmarshalJSON ¶ added in v0.10.0
UnmarshalJSON implements json.Unmarshaler for Option[T]. If the JSON is null, it creates a None option. Otherwise, it unmarshals the value into Some.
func (Option[T]) Unwrap ¶
Unwrap extracts the contained value and a boolean indicating if it exists. Returns the value and true if the option is Some, a zero value and false if None.
func (Option[T]) UnwrapOr ¶
func (o Option[T]) UnwrapOr(value T) T
UnwrapOr returns the contained value or a provided default. If the option is Some, returns the contained value, otherwise returns the provided default.
func (Option[T]) UnwrapOrDefault ¶
func (o Option[T]) UnwrapOrDefault() T
UnwrapOrDefault returns the contained value or the zero value. If the option is Some, returns the contained value, otherwise returns the zero value for type T.
func (Option[T]) UnwrapOrElse ¶
func (o Option[T]) UnwrapOrElse(fn func() T) T
UnwrapOrElse returns the contained value or computes it from a closure. If the option is Some, returns the contained value, otherwise returns the result of calling fn.
func (Option[T]) UnwrapUnsafe ¶
func (o Option[T]) UnwrapUnsafe() T
UnwrapUnsafe returns the contained value or panics. If the option is Some, returns the contained value, otherwise panics with a message. Use this method when you are certain the Option is in the Some state.
type Result ¶
type Result[T any] struct { // contains filtered or unexported fields }
Result represents a computation that may succeed with type T or fail with an error. It is similar to Option but includes error information when the value is absent.
Example ¶
ExampleResult demonstrates basic usage of the Result type.
// Create successful and error results
success := Ok("Hello, World!")
failure := Err[string](errors.New("something went wrong"))
// Check if results are ok
fmt.Printf("Success is ok: %v\n", success.IsOk())
fmt.Printf("Failure is ok: %v\n", failure.IsOk())
// Extract values safely
if value, err := success.Unwrap(); err == nil {
fmt.Printf("Success value: %s\n", value)
}
if _, err := failure.Unwrap(); err != nil {
fmt.Printf("Failure error: %v\n", err)
}
Output: Success is ok: true Failure is ok: false Success value: Hello, World! Failure error: something went wrong
func Err ¶
Err creates a new Result in the error state with the given error. This is a constructor function for creating a Result that represents failure.
Example ¶
ExampleErr demonstrates creating an error Result.
// Create an error result
result := Err[string](errors.New("something failed"))
fmt.Printf("Is error: %t\n", result.IsErr())
fmt.Printf("Value: %s\n", result.UnwrapOr("default"))
Output: Is error: true Value: default
func Ok ¶
Ok creates a new Result in the Ok state with the given value. This is a constructor function for creating a Result that represents success.
Example ¶
ExampleOk demonstrates creating a successful Result.
// Create a successful result
result := Ok("Success!")
fmt.Printf("Is ok: %t\n", result.IsOk())
fmt.Printf("Value: %s\n", result.UnwrapOr("default"))
Output: Is ok: true Value: Success!
func OkZero ¶
OkZero creates a new Result in the Ok state with the zero value. This is a constructor function for creating a Result that represents success but doesn't carry a meaningful value.
Example ¶
ExampleOkZero demonstrates creating a Result with zero value.
// Create a successful result with zero value
result := OkZero[int]()
fmt.Printf("Is ok: %t\n", result.IsOk())
fmt.Printf("Value: %d\n", result.UnwrapOr(-1))
Output: Is ok: true Value: 0
func (Result[T]) And ¶
And returns other if the result is Ok, otherwise returns the error result. This is useful for chaining results where both must succeed.
func (Result[T]) AndThen ¶
AndThen returns a new result with the value computed from fn if the result is Ok, otherwise returns the error result without calling fn. This is useful for chaining operations that might fail.
func (Result[T]) IsErr ¶
IsErr checks if the result represents a failed computation. Returns true if there is an error, false otherwise.
func (Result[T]) IsOk ¶
IsOk checks if the result represents a successful computation. Returns true if there is no error, false otherwise.
func (Result[T]) Map ¶
Map transforms the contained value using the provided function if the result is Ok. If the result is an error, returns the error result without calling the function.
Example ¶
ExampleResult_Map demonstrates transforming values inside Result.
// Start with a result containing a number
result := Ok(5)
// Transform to its square
squared := result.Map(func(x int) int { return x * x })
// Transform an error result
errorResult := Err[int](errors.New("invalid input"))
errorSquared := errorResult.Map(func(x int) int { return x * x })
fmt.Printf("Square of 5: %v\n", squared.UnwrapOr(0))
fmt.Printf("Square of error: %v\n", errorSquared.UnwrapOr(-1))
Output: Square of 5: 25 Square of error: -1
func (Result[T]) MapOr ¶
MapOr transforms the contained value or returns a default. If the result is Ok, applies the function to the contained value, otherwise returns an Ok result with the provided default value.
func (Result[T]) MapOrElse ¶
MapOrElse transforms the contained value or handles the error. If the result is Ok, applies handleOk to the contained value, otherwise calls handleErr with the error. In both cases, returns an Ok result with the computed value.
func (Result[T]) Match ¶
Match allows pattern matching on the Result. If the result is Ok, calls handleOk with the contained value, otherwise calls handleErr with the error.
Example ¶
ExampleResult_Match demonstrates pattern matching with Result.
// Helper function that may fail
divide := func(x, y int) Result[int] {
if y == 0 {
return Err[int](errors.New("division by zero"))
}
return Ok(x / y)
}
// Pattern match on results
success := divide(10, 2)
failure := divide(10, 0)
result1 := success.Match(
func(value int) Result[int] {
return Ok(value * 2)
},
func(err error) Result[int] {
return Err[int](fmt.Errorf("handled: %w", err))
},
)
result2 := failure.Match(
func(value int) Result[int] {
return Ok(value * 2)
},
func(err error) Result[int] {
return Err[int](fmt.Errorf("handled: %w", err))
},
)
fmt.Printf("Success result: %v\n", result1.UnwrapOr(-1))
fmt.Printf("Failure handled: %v\n", result2.IsErr())
Output: Success result: 10 Failure handled: true
func (Result[T]) Or ¶
Or returns the result if it is Ok, otherwise returns the provided result. This is useful for providing a fallback result when the current one might be an error.
Example ¶
ExampleResult_Or demonstrates providing fallback results.
// Create primary and fallback results
primary := Err[string](errors.New("primary failed"))
fallback := Ok("fallback value")
// Use fallback when primary fails
result := primary.Or(fallback)
fmt.Printf("Result: %s\n", result.UnwrapOr("default"))
Output: Result: fallback value
func (Result[T]) OrElse ¶
OrElse returns the result if it is Ok, otherwise calls the function and returns its result. This is a lazy version of Or, as the fallback result is only computed if needed.
func (Result[T]) Unwrap ¶
Unwrap extracts the contained value and any error. Returns the value (which may be the zero value) and the error (which may be nil).
func (Result[T]) UnwrapOr ¶
func (r Result[T]) UnwrapOr(other T) T
UnwrapOr returns the contained value or a provided default. If the result is Ok, returns the contained value, otherwise returns the provided default.
func (Result[T]) UnwrapOrDefault ¶
func (r Result[T]) UnwrapOrDefault() T
UnwrapOrDefault returns the contained value or the zero value. If the result is Ok, returns the contained value, otherwise returns the zero value for type T.
func (Result[T]) UnwrapOrElse ¶
func (r Result[T]) UnwrapOrElse(fn func() T) T
UnwrapOrElse returns the contained value or computes it from a closure. If the result is Ok, returns the contained value, otherwise returns the result of calling fn.
func (Result[T]) UnwrapUnsafe ¶
func (r Result[T]) UnwrapUnsafe() T
UnwrapUnsafe returns the contained value or panics if there is an error. Use this method when you are certain the Result is in the Ok state.