opt

package module
v0.0.0-...-40c0234 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package opt implements a optional type, it may or may not contain a value. It can also be marshalled and unmarshalled with JSON, using the underlying marshelers, if such exist.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Opt

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

Opt is an optional type, it may or may not contatin a value of a certain type, given by its type parameter. Its zero value is called None, when printed: <none>, it indicates the absence of value.

As it stands, an arbitrary Opt can be marshalled and unmarshalled with JSON, with JSON's null being considered the zero value, regardless of the type param.

func None

func None[T any]() Opt[T]

None creates a new Opt value with no value, ie, None.

func Some

func Some[T any](val T) Opt[T]

Some creates a new Opt value with a value.

func (Opt[T]) MarshalJSON

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

MarshalJSON implements the json.Marshaler interface, it marshals the Opt struct, if it is None, it returns JSON's null, otherwise it tries to marshal the underlying value, if it fails, the error is returned.

func (Opt[T]) String

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

String implements the fmt.Stringer interface, it returns the string "<none>" if the Opt is None, otherwise it returns the string representation of the underlying value, using fmt.Sprint.

func (*Opt[T]) UnmarshalJSON

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

UnmarshalJSON implements the json.Unmarshaler interface, it unmarshals the value into the Opt struct, if the input is JSON's null, the Opt is set to None, otherwise it tries to unmarshal the value into the underlying type, if it fails, the Opt is set to None and the error is returned.

func (Opt[T]) Unwrap

func (o Opt[T]) Unwrap() (T, bool)

Unwrap unpacks the Opt struct and returns its components, a common assertion should be done, it may be done in the following way:

val, ok := opt.Unwrap()
if !ok {
	// handle noneness
}

Since this a non-build-in function, the ok return cannot be ommited.

Jump to

Keyboard shortcuts

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