opt

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2024 License: MIT Imports: 3 Imported by: 1

README

opt

A simple Go package that provides a generic Option type: a container that either has a value or is empty.

Run go get hermannm.dev/opt to add it to your project!

Motivation

One of the Go proverbs is to "make the zero value useful". But this is not always practical - for example, one may want to distinguish between a blank string and an optional string that has not been set. In these cases, one may choose to use a pointer instead, with nil as the zero value. But working with pointers can be more cumbersome, risk panics from nil dereferencing, and have negative performance implications if values are moved to the heap.

This package provides an alternative, through the generic Option[T] wrapper type. It aims to provide a zero value for types (the empty option), and clearly signal to readers of the code that the value is optional.

Usage

Option has three constructors:

  • Value(T) creates an Option[T] containing the given value:

    name := opt.Value("hermannm")
    if name.HasValue() {
        fmt.Printf("Hello, %s\n", name.Value)
    }
    
  • Empty() creates an empty option:

    name := opt.Empty[string]()
    if name.IsEmpty() {
        fmt.Println("No name given")
    }
    
  • FromPointer(*T) creates an Option[T] with the pointer's value, or an empty option if the pointer is nil:

    var pointer *string
    option := opt.FromPointer(pointer)
    if value, ok := option.Get(); ok {
        fmt.Printf("Got value %s\n", value)
    } else {
        fmt.Println("No value received")
    }
    

Once an option is created, you can replace/remove its value with Put/Clear:

option := opt.Empty[string]()

option.Put("value")
fmt.Println(option) // Prints "value"

option.Clear()
fmt.Println(option) // Prints "<empty>"

Finally, Option implements json.Marshaler and json.Unmarshaler. An empty option marshals to null, and a null JSON value unmarshals to an empty option:

type Person struct {
    Name opt.Option[string] `json:"name"`
    Age  opt.Option[int]    `json:"age"`
}

person1 := Person{
    Name: opt.Value("hermannm"),
    Age:  opt.Empty[int](),
}
jsonOutput, err := json.Marshal(object1)
// Output: {"name":"hermannm","age":null}

jsonInput := []byte(`{"name":null,"age":25}`)
var person2 Object
err := json.Unmarshal(jsonInput, &person2)
// Name is now empty, while Age has value 25

Documentation

Overview

Package opt provides Option, a container that either has a value or is empty.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Option

type Option[T any] struct {

	// Before accessing Value, you should check if it is present with [Option.HasValue].
	Value T
	// contains filtered or unexported fields
}

Option is a container that either has a value, or is empty. You construct an option with Value, Empty or FromPointer. You can check if an option contains a value or is empty with Option.HasValue or Option.IsEmpty, and access the value through the [Option.Value] field.

The zero value of Option is an empty option.

An empty option marshals to `null` in JSON, and a `null` JSON value unmarshals to an empty option.

func Empty

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

Empty creates an empty Option.

func FromPointer

func FromPointer[T any](pointer *T) Option[T]

FromPointer creates an Option with the value pointed to by the given pointer, dereferencing it. If the pointer is nil, an empty option is returned.

func FromSQL added in v0.1.2

func FromSQL[T any](sql sql.Null[T]) Option[T]

FromSQL creates an Option from the given sql.Null value. A null SQL value becomes an empty option, and a non-null SQL value becomes an option containing the value.

func Value

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

Value creates an Option that contains the given value.

func (*Option[T]) Clear

func (option *Option[T]) Clear()

Clear removes the current value of the option, if any. After this call, Option.IsEmpty will return true.

func (Option[T]) Get

func (option Option[T]) Get() (value T, ok bool)

Get returns the value of the option, and an `ok` flag that is true if the option contained a value, and false if it is empty. You should only use the returned value if `ok` is true.

func (Option[T]) GetOrDefault added in v0.1.2

func (option Option[T]) GetOrDefault(defaultValue T) T

GetOrDefault returns the option's value if present, or the given default value if the option is empty.

func (Option[T]) HasValue

func (option Option[T]) HasValue() bool

HasValue returns true if the option contains a value.

func (Option[T]) IsEmpty

func (option Option[T]) IsEmpty() bool

IsEmpty returns true if the option does not contain a value.

func (Option[T]) MarshalJSON

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

MarshalJSON implements the json.Marshaler interface for Option. If the option contains a value, it marshals that value. If the option is empty, it marshals to `null`.

func (*Option[T]) Put

func (option *Option[T]) Put(value T)

Put replaces the current value of the option, if any, with the given value. After this call, Option.HasValue will return true.

func (Option[T]) String

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

String returns the string representation of the option's value. If the option is empty, it returns the string `<empty>` (similar to the string representation `<nil>` for nil pointers).

func (Option[T]) ToPointer added in v0.1.1

func (option Option[T]) ToPointer() *T

ToPointer returns nil if the option is empty, otherwise it returns a pointer to the option's value.

It is meant to be used for compatibility with libraries that use pointers for optional values.

func (Option[T]) ToSQL added in v0.1.2

func (option Option[T]) ToSQL() sql.Null[T]

ToSQL converts the option to an sql.Null. An empty option becomes null.

func (*Option[T]) UnmarshalJSON

func (option *Option[T]) UnmarshalJSON(jsonValue []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Option. If the given JSON value is `null`, it unmarshals to an empty option. Otherwise, it tries to unmarshal to the value contained by the option.

Jump to

Keyboard shortcuts

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