opt

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2022 License: MIT Imports: 1 Imported by: 0

README

Option

This package implements a Rust styled Option type for optional values in Go. Option provides a wrapper around a value that may or may not be initialized and a set of methods to extract the inner value or handle nil cases.

Usage

Installation
go get -u github.com/heat1q/opt
Example
package main

import (
	"fmt"

	"github.com/heat1q/opt"
)

func main() {
	o := opt.New("potato")
	value, ok := o.Some()
	fmt.Println(ok) // true
	fmt.Println(value) // potato
}

Marshalling JSON

Option solves the nullable issue for values where the default of a value is also considered valid. For instance, consider the scenario where the false value of a bool is a valid instance of the nullable field.

package main

import (
	"fmt"

	"github.com/heat1q/opt"
)

type data struct {
	Flag opt.Option[bool] `json:"flag,omitempty"`
}

func main() {
	var d data

	_ = json.Unmarshal(`{}`, &d)
	_, ok := d.Value.Some() 
	fmt.Println(ok) // false
	
	_ = json.Unmarshal(`{"flag": false}`, &d)
	_, ok = d.Value.Some() 
	fmt.Println(ok) // true
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Option

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

Option represent an optional value.

func New

func New[T any](val T) Option[T]

New creates a new Option.

func (*Option[T]) MarshalJSON

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

func (Option[T]) None

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

None asserts if the value is nil.

func (Option[T]) Some

func (o Option[T]) Some() (T, bool)

Some returns the value, if any, and a bool indicating if the value is non-nil.

func (*Option[T]) UnmarshalJSON

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

func (Option[T]) Unwrap

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

Unwrap extracts the value. It panics if the inner value is nil

func (Option[T]) UnwrapOr

func (o Option[T]) UnwrapOr(val T) T

UnwrapOr extracts the value. If the inner value is nil it returns the value specified by `val`.

func (Option[T]) UnwrapOrDefault

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

UnwrapOrDefault extracts the value. It returns the type specific default value if the inner value is nil.

func (Option[T]) UnwrapOrElse

func (o Option[T]) UnwrapOrElse(f func() T) T

UnwrapOrElse extracts the value. If the inner value is nil it executes the specified function and returns its value.

Jump to

Keyboard shortcuts

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