nilo

package module
v1.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 19, 2026 License: MIT Imports: 4 Imported by: 8

README

nilo

Go Option library for handling nil values, some errors and JSON marshaling

Caveats

  • This library requires Go 1.23+

Installation

go get -u github.com/javiorfo/nilo@latest

Example

Examples here
package main

import (
  "errors"
  "fmt"

  "github.com/javiorfo/nilo"
)

type User struct {
  Name string
}

// Implements nilo.Default interface
func (u User) Default() User {
  return User{"Default Implementation"}
}

func main() {
  var optUser = nilo.Nil[User]()

  fmt.Printf("User or default: %+v\n", optUser.OrDefault())
  fmt.Printf("User or: %+v\n", optUser.Or(*new(User)))
  fmt.Printf("User or else: %+v\n", optUser.OrElse(func() User { return User{"else"} }))
  fmt.Printf("Map or: %+v\n", optUser.Map(func(u User) User {
	  u.Name = "something"
	  return u
  }).Or(User{"or"}))

  nilo.FromResult(getUser(true)).
    AndResult(getUser2).
    Consume(print)

  _, err := test(false).OrError(func() error { return errors.New("some err") })
  fmt.Println("Error:", err.Error())

  fmt.Println(test(true).
    MapToString(func(v string) string { return v + ", World" }).
    Or("another string"))
}

func test(b bool) nilo.Option[string] {
  if b {
	  return nilo.Value("Hello")
  }
  return nilo.Nil[string]()
}

func print[T any](v *T) {
  fmt.Printf("Value: %#v\n", *v)
}

func getUser(b bool) (*int, error) {
  if b {
	  i := 1
	  return &i, nil
  }
  return nil, errors.New("error")
}

func getUser2(v *int) (*int, error) {
  if *v == 0 {
	  return nil, errors.New("error")
  }
  i := *v + 2
  return &i, nil
}
JSON marshal
package main

import (
  "encoding/json"
  "fmt"

  "github.com/javiorfo/nilo"
)

type User struct {
  Name string              `json:"name"`
  Code nilo.Option[string] `json:"code"`
}

func main() {
  var unmarshalUser User
  user := User{
	  Name: "Name",
	  Code: nilo.Nil[string](),
  }

  // Marshal
  jsonData, err := json.MarshalIndent(user, "", "  ")
  if err != nil {
	  fmt.Println("Error marshaling to JSON:", err)
	  return
  }

  fmt.Println(string(jsonData))
	
  // Unmarshal
  err = json.Unmarshal(jsonData, &unmarshalUser)
  if err != nil {
	  fmt.Println("Error unmarshaling:", err)
	  return
  }
	
  fmt.Printf("Unmarshaled User: %+v\n", unmarshalUser)
  if unmarshalUser.Code.IsNil() {
	  fmt.Printf("Code is Nil: %s\n", unmarshalUser.Code)
  }

  // Put Some in Code
  user.Code.Insert("code")

  // Marshal
  jsonData, err = json.MarshalIndent(user, "", "  ")
  if err != nil {
	  fmt.Println("Error marshaling to JSON:", err)
	  return
  }

  fmt.Println(string(jsonData))

  // Unmarshal
  err = json.Unmarshal(jsonData, &unmarshalUser)
  if err != nil {
	  fmt.Println("Error unmarshaling:", err)
	  return
  }
	
  fmt.Printf("Unmarshaled User: %+v\n", unmarshalUser)
  if unmarshalUser.Code.IsValue() {
	  fmt.Printf("Code is Value: %s\n", unmarshalUser.Code)
  }
}
All methods and functions
func (o Option[T]) AsValue() T
func (o Option[T]) AsPtr() *T
func (o Option[T]) Or(other T) T
func (o Option[T]) OrDefault() T
func (o Option[T]) OrElse(supplier func() T) T
func (o Option[T]) OrError(err func() error) (*T, error)
func (o Option[T]) OrPanic(msg string) T
func (o Option[T]) Filter(filter func(T) bool) Option[T]
func (o Option[T]) IsNil() bool
func (o Option[T]) IsValue() bool
func (o Option[T]) IsValueAnd(predicate func(T) bool) bool
func (o Option[T]) IsNilOr(predicate func(T) bool) bool
func (o Option[T]) IfNil(executor func())
func (o Option[T]) Inspect(inspector func(T)) Option[T]
func (o Option[T]) Consume(consumer func(T))
func (o *Option[T]) Take() Option[T]
func (o *Option[T]) TakeIf(predicate func(T) bool) Option[T]
func (o *Option[T]) Insert(value T)
func (o Option[T]) Map(mapper func(T) T) Option[T]
func (o Option[T]) MapToString(mapper func(T) string) Option[string]
func (o Option[T]) MapToInt(mapper func(T) int) Option[int]
func (o Option[T]) MapToBool(mapper func(T) bool) Option[bool]
func (o Option[T]) MapOrDefault(mapper func(T) T) T
func (o Option[T]) AndThen(fn func(T) Option[T]) Option[T]
func (o Option[T]) AndOk(apply func(T) (T, error)) Option[T]
func (o Option[T]) AndOkPtr(apply func(T) (*T, error)) Option[T]
func (o Option[T]) MarshalJSON() ([]byte, error)
func (o *Option[T]) UnmarshalJSON(data []byte) error
func (o Option[T]) String() string
func (o Option[T]) Iter() iter.Seq[T] {
func Ok[T any](value T, err error) Option[T]
func Nil[T any]() Option[T]
func Value[T any](value T) Option[T]
func Ptr[T any](value *T) Option[T]
func Cast[T any](value T) Option[T]

Donate
  • Bitcoin (QR) 1GqdJ63RDPE4eJKujHi166FAyigvHu5R7v
  • Paypal

Documentation

Overview

Package nilo provides a generic Option type that can be used to represent a value that may or may not be present.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ReturnError added in v1.4.0

func ReturnError(err error) func() error

Simple function to wrap in OrError method

Types

type Default added in v1.1.0

type Default[T any] interface {
	Default() T
}

Default is an interface that can be implemented by types that wish to provide a custom 'default' value. This is used by methods on `Option` such as `OrDefault` or `MapOrDefault` to create an instance of the type when a `Nil` `Option` is encountered.

Types that implement this interface can define their own logic for what constitutes a 'default' value, instead of relying on the Go language's zero value.

type Option added in v1.1.0

type Option[T any] struct {
	// contains filtered or unexported fields
}

Option is a generic type that represents an option value. An `Option` can either be `Value`, containing a value of type `T`, or `Nil`, indicating the absence of a value.

func Cast added in v1.5.0

func Cast[T any](value any) Option[T]

Cast attempts to assert the value any to type T. If the type assertion is successful, it returns an Option containing the value. If the assertion fails (e.g., incompatible types or i is nil), it returns a Nil Option.

Example:

opt := Cast[int](anyValue)

func Nil added in v1.4.0

func Nil[T any]() Option[T]

Nil returns an empty Option.

func Ok added in v1.6.0

func Ok[T any](value T, err error) Option[T]

Ok creates an `Option` from a Go function's return values.

It returns a `Value` `Option` containing `value` if `err` is `nil`. If `err` is not `nil`, it returns a `Nil` `Option`. This is a convenient way to bridge error-handling patterns in Go with the `Option` type.

Parameters:

  • value: The value to wrap in a `Value` `Option` if there is no error.
  • err: The error returned from a function.

func Ptr added in v1.4.0

func Ptr[T any](value *T) Option[T]

Ptr creates an Option from a pointer to a value. If the pointer is nil, it returns an empty Option.

func Value added in v1.4.0

func Value[T any](value T) Option[T]

Value creates an Option containing the provided value.

func (Option[T]) AndOk added in v1.6.0

func (o Option[T]) AndOk(apply func(T) (T, error)) Option[T]

AndOk applies a function that returns a value and an error to the `Option`'s contained value.

If the `Option` is `Value` and the applied function returns a `nil` error, this method returns a `Value` `Option` with the function's returned value. In all other cases (if the `Option` is `Nil` or the function returns a non-nil error), it returns a `Nil` `Option`. This is useful for chaining operations that might fail.

Parameters:

  • apply: A function that takes the `Option`'s value and returns a new value and an error.

func (Option[T]) AndOkPtr added in v1.6.0

func (o Option[T]) AndOkPtr(apply func(T) (*T, error)) Option[T]

AndOkPtr applies a function that returns a pointer value and an error to the `Option`'s contained value.

If the `Option` is `Value` and the applied function returns a `nil` error, this method returns a `Value` `Option` with the function's returned value. In all other cases (if the `Option` is `Nil` or the function returns a non-nil error or a nil value), it returns a `Nil` `Option`. This is useful for chaining operations that might fail.

Parameters:

  • apply: A function that takes the `Option`'s value and returns a new pointer value and an error.

func (Option[T]) AndThen added in v1.1.0

func (o Option[T]) AndThen(fn func(T) Option[T]) Option[T]

AndThen is a chaining method that applies a function to the contained value if the `Option` is `Value`, returning the result.

If the `Option` is `Value`, the `fn` is called with the unwrapped value, and the new `Option` returned by `fn` is the result. This allows for a sequence of fallible operations. If the `Option` is `Nil`, this method returns `Nil` without calling `fn`.

Parameters:

  • fn: A function that takes the `Option`'s value and returns a new `Option`.

func (Option[T]) AsPtr added in v1.4.0

func (o Option[T]) AsPtr() *T

AsPtr returns the pointer of the contained value without checking if the `Option` is `Value`.

The caller is responsible for ensuring the `Option` is `Value` before calling this method. Calling this on a `Nil` `Option` will result in a nil pointer.

func (Option[T]) AsValue added in v1.4.0

func (o Option[T]) AsValue() T

AsValue returns the contained value of an `Option`.

Panics if the `Option` is `Nil`. This method should only be used when you are certain the `Option` contains a value.

func (Option[T]) Consume added in v1.3.0

func (o Option[T]) Consume(consumer func(T))

Consume calls a function on the contained value if the `Option` is `Value`, and returns nothing.

This is often used for side effects, such as updating state, without needing to manually check the presence of the value.

Parameters:

  • consumer: A function that takes the `Option`'s value.

func (Option[T]) Filter added in v1.1.0

func (o Option[T]) Filter(filter func(T) bool) Option[T]

Filter calls a predicate function on the contained value if the `Option` is `Value`.

If the `Option` is `Value` and the predicate returns `true`, it returns a `Value` `Option` with the original value. Otherwise, it returns a `Nil` `Option`. This is useful for removing values that do not meet a certain condition.

Parameters:

  • filter: A predicate function that returns `true` or `false` based on the value.

func (Option[T]) IfNil added in v1.5.0

func (o Option[T]) IfNil(executor func())

IfNil calls a function if the `Option` is `Nil`, and returns nothing.

Parameters:

  • executor: A function that takes the no arguments..

func (*Option[T]) Insert added in v1.1.0

func (o *Option[T]) Insert(value T)

Insert replaces the contained value with a new one.

If the `Option` is currently `Nil`, it is changed to `Value` with the new value. If the `Option` is already `Value`, its existing value is replaced by the new one.

Parameters:

  • value: The new value to be inserted into the `Option`.

func (Option[T]) Inspect added in v1.1.0

func (o Option[T]) Inspect(inspector func(T)) Option[T]

Inspect calls a function on the contained value if the `Option` is `Value`, and then returns the original `Option`.

This is useful for debugging or logging the value without consuming the `Option`.

Parameters:

  • inspector: A function that takes the `Option`'s value.

func (Option[T]) IsNil added in v1.4.0

func (o Option[T]) IsNil() bool

IsNil returns `true` if the `Option` is `Nil`.

func (Option[T]) IsNilOr added in v1.4.0

func (o Option[T]) IsNilOr(predicate func(T) bool) bool

IsNilOr returns `true` if the `Option` is `Nil` or if the contained value satisfies the given `predicate`.

This acts as a logical "OR" on the state of the `Option`. If the `Option` is `Nil`, the predicate is not evaluated, and `true` is returned. If it is `Value`, the function returns the result of the `predicate`.

Parameters:

  • predicate: A function that takes the `Option`'s value and returns a boolean.

func (Option[T]) IsValue added in v1.4.0

func (o Option[T]) IsValue() bool

IsValue returns `true` if the `Option` is `Value`.

func (Option[T]) IsValueAnd added in v1.4.0

func (o Option[T]) IsValueAnd(predicate func(T) bool) bool

IsValueAnd returns `true` if the `Option` is `Value` and the value contained within it satisfies the given `predicate`.

If the `Option` is `Nil`, this method short-circuits and returns `false`. This is a convenient way to check for both presence and a condition in one call.

Parameters:

  • predicate: A function that takes the `Option`'s value and returns a boolean.

func (Option[T]) Iter added in v1.6.0

func (o Option[T]) Iter() iter.Seq[T]

Iter returns an iterator that yields the value held by the Option. If the Option is empty, the iterator yields nothing.

func (Option[T]) Map added in v1.1.0

func (o Option[T]) Map(mapper func(T) T) Option[T]

Map applies a function to the contained value of an Option if it is `Value` and returns a new `Option` containing the mapped value.

If the original `Option` is `Nil`, this method returns `Nil`.

Parameters:

  • mapper: The function to apply to the `Option`'s value. It takes a value of type `T` and returns a value of the same type `T`.

Returns:

  • A new `Option[T]` containing the result of the mapping, or `Nil` if the original `Option` was `Nil`.

func (Option[T]) MapOrDefault added in v1.1.0

func (o Option[T]) MapOrDefault(mapper func(T) T) T

MapOrDefault maps the `Option`'s value if it is `Value`, otherwise returns the zero value of the type or the implemented in Default interface.

Parameters:

  • mapper: A function to apply to the `Option`'s value if it is `Value`.

func (Option[T]) MapToBool added in v1.1.0

func (o Option[T]) MapToBool(mapper func(T) bool) Option[bool]

MapToBool maps the contained value of an `Option[T]` to a boolean if it is `Value`, and returns a new `Option[bool]` with the result.

If the original `Option` is `Nil`, this method returns `Nil bool`.

Parameters:

  • mapper: The function to apply to the `Option`'s value. It takes a value of type `T` and returns a `bool`.

Returns:

  • A new `Option[bool]` containing the mapped value, or `Nil bool` if the original `Option` was `Nil`.

func (Option[T]) MapToInt added in v1.1.0

func (o Option[T]) MapToInt(mapper func(T) int) Option[int]

MapToInt maps the contained value of an `Option[T]` to an integer if it is `Value`, and returns a new `Option[int]` with the result.

If the original `Option` is `Nil`, this method returns `Nil int`.

Parameters:

  • mapper: The function to apply to the `Option`'s value. It takes a value of type `T` and returns an `int`.

Returns:

  • A new `Option[int]` containing the mapped value, or `Nil int` if the original `Option` was `Nil`.

func (Option[T]) MapToString added in v1.1.0

func (o Option[T]) MapToString(mapper func(T) string) Option[string]

MapToString maps the contained value of an `Option[T]` to a string if it is `Value`, and returns a new `Option[string]` with the result.

If the original `Option` is `Nil`, this method returns `Nil string`.

Parameters:

  • mapper: The function to apply to the `Option`'s value. It takes a value of type `T` and returns a `string`.

Returns:

  • A new `Option[string]` containing the mapped value, or `Nil string` if the original `Option` was `Nil`.

func (Option[T]) MarshalJSON added in v1.1.0

func (o Option[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements the `json.Marshaler` interface for `Option`.

If the `Option` is `Nil`, it marshals to the JSON value `null`. If the `Option` is `Value`, it marshals the wrapped value to its JSON representation.

func (Option[T]) Or added in v1.1.0

func (o Option[T]) Or(other T) T

Or returns the contained value if the `Option` is `Value`, otherwise returns the provided default value `other`.

This is a safe alternative to `AsValue` when you have a default value to use.

Parameters:

  • other: The default value to return if the `Option` is `Nil`.

func (Option[T]) OrDefault added in v1.4.0

func (o Option[T]) OrDefault() T

OrDefault returns the contained value if the `Option` is `Value`. If the `Option` is `Nil`, it returns a default value.

The default value is determined by the following:

  1. If the type `T` implements the `Default` interface, `Default()` is called to get the default value.
  2. Otherwise, the Go language's zero value for type `T` is returned.

func (Option[T]) OrElse added in v1.1.0

func (o Option[T]) OrElse(supplier func() T) T

OrElse returns the contained value if the `Option` is `Value`, otherwise it calls the provided `supplier` function to get a default value.

This is useful for providing a default value that is expensive to compute, as the supplier function is only called when needed.

Parameters:

  • supplier: A function that returns the default value if the `Option` is `Nil`.

func (Option[T]) OrError added in v1.4.0

func (o Option[T]) OrError(err func() error) (*T, error)

OrError converts an `Option` into a `(value, error)` tuple.

If the `Option` is `Value`, it returns a pointer to the value and a `nil` error. If the `Option` is `Nil`, it returns a `nil` pointer and the error returned by the `err` supplier function. This is useful when creating the error is an expensive operation, as the supplier function is only called when needed.

Parameters:

  • err: A function that returns the error to be used if the `Option` is `Nil`.

func (Option[T]) OrPanic added in v1.4.0

func (o Option[T]) OrPanic(msg string) T

OrPanic returns the contained `Value` value, but panics with a custom message if the `Option` is `Nil`.

This method is used when a `Nil` value is considered an unrecoverable error in your program, and you want to crash with a descriptive message.

Parameters:

  • msg: The message to be used in the panic if the `Option` is `Nil`.

func (Option[T]) String added in v1.1.0

func (o Option[T]) String() string

String implements the `fmt.Stringer` interface for `Option`.

It returns a string representation of the `Option`. For `Value` `Option`s, the format is "Value". For a `Nil` `Option`, the format is "Nil".

func (*Option[T]) Take added in v1.1.0

func (o *Option[T]) Take() Option[T]

Take takes the value out of the `Option`, leaving a `Nil` in its place.

If the `Option` is `Value`, this method returns the original `Value` `Option` and sets the receiver to `Nil`. If the `Option` is `Nil`, it remains `Nil`.

func (*Option[T]) TakeIf added in v1.1.0

func (o *Option[T]) TakeIf(predicate func(T) bool) Option[T]

TakeIf takes the value out of the `Option` and leaves a `Nil` if the contained value satisfies the given `predicate`.

If the `Option` is `Value` and the `predicate` returns `true`, it behaves identically to `Take`, returning the original `Value` `Option` and setting the receiver to `Nil`. Otherwise, it returns `Nil` and does not modify the original `Option`.

Parameters:

  • predicate: A function that tests the `Option`'s value.

func (*Option[T]) UnmarshalJSON added in v1.1.0

func (o *Option[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the `json.Unmarshaler` interface for `Option`.

If the JSON data is `null`, it unmarshals into a `Nil` `Option`. Otherwise, it unmarshals the data into the `Option`'s value, creating a `Value` `Option` with the unmarshaled content.

Directories

Path Synopsis
examples
marshal command
simple command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL