opt

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2025 License: MIT Imports: 1 Imported by: 0

README

opt

test Go Reference

The opt package provides a generic type for optional values.

Features

  • Generic: T[U] struct holds any type of value.
  • Sortable: implements "cmp"-like helper functions Less and Compare (only for U satisfied cmp.Ordered constraint).
  • Serializable: TODO

Usage

Here's a simple example demonstrating how to use the opt package:

Example
package main

import (
	"fmt"

	"github.com/WinPooh32/opt"
)

func main() {
	var v opt.T[int]

	v = opt.Wrap(1)

	if v.Set() {
		fmt.Println(v.Value())
	}
}

Documentation

Overview

Example
package main

import (
	"fmt"

	"github.com/WinPooh32/opt"
)

func main() {
	o1 := opt.Wrap(1)

	if v, ok := opt.Unwrap(o1); ok {
		fmt.Println(v)
	}

	o2 := opt.Wrap(2)

	if o2.Set() {
		fmt.Println(o2.Value())
	}

	fmt.Println(opt.Less(o1, o2))

	fmt.Println(opt.Compare(o1, o2))

}
Output:

1
2
true
-1

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Compare

func Compare[U cmp.Ordered](x, y T[U]) int

Compare returns

-1 if x is less than y,
0 if x equals y,
+1 if x is greater than y

Unset value is always considered less.

func Less

func Less[U cmp.Ordered](x, y T[U]) bool

Less returns true when x is less than y. Unset value is always considered less.

func Unwrap

func Unwrap[U any](x T[U]) (U, bool)

Unwrap returns x content as tuple as the value and set indicator.

Types

type T

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

T contains optional value of any type. Empty value can be used.

func Empty added in v0.0.2

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

Empty returns empty container of any type U.

func Wrap

func Wrap[U any](value U) T[U]

Wrap wraps the value as optional type.

func (T[U]) Set

func (x T[U]) Set() bool

Set returns true when the value is set.

func (T[U]) Value

func (x T[U]) Value() U

Value returns contained value.

Jump to

Keyboard shortcuts

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