gust

package module
v1.5.2 Latest Latest
Warning

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

Go to latest
Published: May 11, 2023 License: MIT Imports: 7 Imported by: 8

README

gust

tag Go Version GoDoc Build Status Go report Coverage License

A Rust-inspired declarative-programming and generic-type module for Golang that helps avoid bugs and improve development efficiency.

declarative_vs_imperative.jpg

After using this package, your code style will be like this:

package examples_test

import (
	"errors"
	"fmt"

	"github.com/andeya/gust"
	"github.com/andeya/gust/iter"
	"github.com/andeya/gust/ret"
)

type Version int8

const (
	Version1 Version = iota + 1
	Version2
)

func ParseVersion(header iter.Iterator[byte]) gust.Result[Version] {
	return ret.AndThen(
		header.Next().
			OkOr("invalid header length"),
		func(b byte) gust.Result[Version] {
			switch b {
			case 1:
				return gust.Ok(Version1)
			case 2:
				return gust.Ok(Version2)
			}
			return gust.Err[Version]("invalid version")
		},
	)
}

func ExampleVersion() {
	ParseVersion(iter.FromElements[byte](1, 2, 3, 4)).
		Inspect(func(v Version) {
			fmt.Printf("working with version: %v\n", v)
		}).
		InspectErr(func(err error) {
			fmt.Printf("error parsing header: %v\n", err)
		})
	// Output:
	// working with version: 1
}

Go Version

go≥1.19

Features

  • gust.Result is a type that represents either a success or an error.
  • gust.Option is a type that represents either a value or nothing.
  • gust.Mutex is a better generic-type wrapper for sync.Mutex that holds a value.
  • gust.RWMutex is a better generic-type wrapper for sync.RWMutex that holds a value.
  • gust.SyncMap is a better generic-type wrapper for sync.Map.
  • gust.AtomicValue is a better generic-type wrapper for atomic.Value.
  • iter is a package that provides a generic-type iterator.
  • vec is a package of generic-type functions for slices.
  • valconv is a package that provides a generic-type value converter.
  • digit is a package of generic-type functions for digit.
  • and more...
Result

Improve func() (T,error), handle result with chain methods.

  • Result Example
func TestResult(t *testing.T) {
	var goodResult1 = gust.Ok(10)
	var badResult1 = gust.Err[int](10)

	// The `IsOk` and `IsErr` methods do what they say.
	assert.True(t, goodResult1.IsOk() && !goodResult1.IsErr())
	assert.True(t, badResult1.IsErr() && !badResult1.IsOk())

	// `map` consumes the `Result` and produces another.
	var goodResult2 = goodResult1.Map(func(i int) int { return i + 1 })
	var badResult2 = badResult1.Map(func(i int) int { return i - 1 })

	// Use `AndThen` to continue the computation.
	var goodResult3 = ret.AndThen(goodResult2, func(i int) gust.Result[bool] { return gust.Ok(i == 11) })

	// Use `OrElse` to handle the error.
	var _ = badResult2.OrElse(func(err error) gust.Result[int] {
		fmt.Println(err)
		return gust.Ok(20)
	})

	// Consume the result and return the contents with `Unwrap`.
	var _ = goodResult3.Unwrap()
}
Option

Improve func()(T, bool) and if *U != nil, handle value with Option type.

Type [Option] represents an optional value, and has a number of uses:

  • Initial values
  • Return values for functions that are not defined over their entire input range (partial functions)
  • Return value for otherwise reporting simple errors, where [None] is returned on error
  • Optional struct fields
  • Optional function arguments
  • Nil-able pointers
  • Option Example
func TestOption(t *testing.T) {
	var divide = func(numerator, denominator float64) gust.Option[float64] {
		if denominator == 0.0 {
			return gust.None[float64]()
		}
		return gust.Some(numerator / denominator)
	}
	// The return value of the function is an option
	divide(2.0, 3.0).
		Inspect(func(x float64) {
			// Pattern match to retrieve the value
			t.Log("Result:", x)
		}).
		InspectNone(func() {
			t.Log("Cannot divide by 0")
		})
}
Errable

Improve func() error, handle error with chain methods.

  • Errable Example
func ExampleErrable() {
	var hasErr = true
	var f = func() gust.Errable[int] {
		if hasErr {
			return gust.ToErrable(1)
		}
		return gust.NonErrable[int]()
	}
	var r = f()
	fmt.Println(r.IsErr())
	fmt.Println(r.UnwrapErr())
	fmt.Printf("%#v", r.ToError())
	// Output:
	// true
	// 1
	// &gust.errorWithVal{val:1}
}
Iterator

Feature-rich iterators.

  • Iterator Example
func TestAny(t *testing.T) {
	var iter = FromVec([]int{1, 2, 3})
	if !iter.Any(func(x int) bool {
		return x > 1
	}) {
		t.Error("Any failed")
	}
}

Documentation

Index

Examples

Constants

View Source
const ErrLazyValueWithoutInit = "*LazyValue[T]: onceInit function is nil"

Variables

This section is empty.

Functions

func CatchEnumResult added in v1.4.2

func CatchEnumResult[U any, E any](result *EnumResult[U, E])

CatchEnumResult catches panic caused by EnumResult[T, E].UnwrapOrThrow() or Errable[E].TryThrow(), and sets E to *EnumResult[U,E] Example:

```go
func example() (result EnumResult[int, string]) {
	defer CatchEnumResult[int, string](&result)
	EnumErr[string, string]("error").UnwrapOrThrow()
	return
}
```

func CatchErrable added in v1.4.3

func CatchErrable[E any](result *Errable[E])

CatchErrable catches panic caused by Errable[E].TryThrow() and sets E to *Errable[E] Example:

```go
func example() (errable Errable[string]) {
	defer CatchErrable[E](&errable)
	ToErrable("panic error").TryThrow()
	return ToErrable("return error")
}
```

func CatchResult added in v1.4.2

func CatchResult[U any](result *Result[U])

CatchResult catches panic caused by Result[T].UnwrapOrThrow() and sets error to *Result[U] Example:

```go
func example() (result Result[string]) {
   defer CatchResult(&result)
   Err[int]("int error").UnwrapOrThrow()
   return Ok[string]("ok")
}
```

func TryPanic added in v1.2.1

func TryPanic[E any](errVal E)

TryPanic panics if the errVal is not nil.

func TryThrow added in v1.4.3

func TryThrow[E any](errVal E)

TryThrow panic returns E (panicValue[*E]) if the errVal is not nil. NOTE:

If there is an E, that panic should be caught with CatchErrable[E] or CatchEnumResult[U, E].

Types

type AnyCtrlFlow added in v0.7.0

type AnyCtrlFlow = SigCtrlFlow[any]

AnyCtrlFlow is a placeholder for wildcard control flow statements.

func AnyBreak added in v0.7.0

func AnyBreak(b any) AnyCtrlFlow

AnyBreak returns a AnyCtrlFlow that tells the operation to break.

func AnyContinue added in v0.7.0

func AnyContinue(c any) AnyCtrlFlow

AnyContinue returns a AnyCtrlFlow that tells the operation to continue.

type AtomicValue added in v1.4.0

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

AtomicValue is a better generic-type wrapper for `atomic.Value`. A AtomicValue provides an atomic load and store of a consistently typed value. The zero value for a AtomicValue returns nil from Load. Once Store has been called, a AtomicValue must not be copied.

A AtomicValue must not be copied after first use.

func (*AtomicValue[T]) CompareAndSwap added in v1.4.0

func (v *AtomicValue[T]) CompareAndSwap(old T, new T) (swapped bool)

CompareAndSwap executes the compare-and-swap operation for the AtomicValue.

All calls to CompareAndSwap for a given AtomicValue must use values of the same concrete type. CompareAndSwap of an inconsistent type panics, as does CompareAndSwap(old, nil).

func (*AtomicValue[T]) Load added in v1.4.0

func (v *AtomicValue[T]) Load() (val Option[T])

Load returns the value set by the most recent Store. It returns None if there has been no call to Store for this AtomicValue.

func (*AtomicValue[T]) Store added in v1.4.0

func (v *AtomicValue[T]) Store(val T)

Store sets the value of the AtomicValue to x. All calls to Store for a given AtomicValue must use values of the same concrete type. Store of an inconsistent type panics, as does Store(nil).

func (*AtomicValue[T]) Swap added in v1.4.0

func (v *AtomicValue[T]) Swap(new T) (old Option[T])

Swap stores new into AtomicValue and returns the previous value. It returns None if the AtomicValue is empty.

All calls to Swap for a given AtomicValue must use values of the same concrete type. Swap of an inconsistent type panics, as does Swap(nil).

type CtrlFlow added in v0.7.0

type CtrlFlow[B any, C any] struct {
	// contains filtered or unexported fields
}

CtrlFlow is used to tell an operation whether it should exit early or go on as usual.

This is used when exposing things (like graph traversals or visitors) where you want the user to be able to choose whether to exit early.

func Break added in v0.7.0

func Break[B any, C any](b B) CtrlFlow[B, C]

Break returns a CtrlFlow that tells the operation to break.

func Continue added in v0.7.0

func Continue[B any, C any](c C) CtrlFlow[B, C]

Continue returns a CtrlFlow that tells the operation to continue.

func (CtrlFlow[B, C]) BreakValue added in v0.7.0

func (c CtrlFlow[B, C]) BreakValue() Option[B]

BreakValue returns the inner value of a `Break` variant.

func (CtrlFlow[B, C]) ContinueValue added in v0.7.0

func (c CtrlFlow[B, C]) ContinueValue() Option[C]

ContinueValue returns the inner value of a `Continue` variant.

func (CtrlFlow[B, C]) EnumResult added in v0.7.0

func (c CtrlFlow[B, C]) EnumResult() EnumResult[C, B]

EnumResult converts the `CtrlFlow[B,C]` to an `EnumResult[C,B]`.

func (CtrlFlow[B, C]) Errable added in v0.7.0

func (c CtrlFlow[B, C]) Errable() Errable[B]

Errable converts the `CtrlFlow[B,C]` to an `Errable[B]`.

func (CtrlFlow[B, C]) IsBreak added in v0.7.0

func (c CtrlFlow[B, C]) IsBreak() bool

IsBreak returns `true` if this is a `Break` variant.

func (CtrlFlow[B, C]) IsContinue added in v0.7.0

func (c CtrlFlow[B, C]) IsContinue() bool

IsContinue returns `true` if this is a `Continue` variant.

func (CtrlFlow[B, C]) Map added in v0.7.0

func (c CtrlFlow[B, C]) Map(f func(B) B, g func(C) C) CtrlFlow[B, C]

Map maps both `Break` and `Continue` values by applying a function to the respective value in case it exists.

func (CtrlFlow[B, C]) MapBreak added in v0.7.0

func (c CtrlFlow[B, C]) MapBreak(f func(B) B) CtrlFlow[B, C]

MapBreak maps `Break` value by applying a function to the break value in case it exists.

func (CtrlFlow[B, C]) MapContinue added in v0.7.0

func (c CtrlFlow[B, C]) MapContinue(f func(C) C) CtrlFlow[B, C]

MapContinue maps `Continue` value by applying a function to the continue value in case it exists.

func (CtrlFlow[B, C]) Option added in v0.7.0

func (c CtrlFlow[B, C]) Option() Option[C]

Option converts the `CtrlFlow` to an `Option`.

func (CtrlFlow[B, C]) Result added in v0.7.0

func (c CtrlFlow[B, C]) Result() Result[C]

Result converts the `CtrlFlow[B,C]` to an `Result[C]`.

func (CtrlFlow[B, C]) String added in v1.0.0

func (c CtrlFlow[B, C]) String() string

String returns the string representation.

func (CtrlFlow[B, C]) ToX added in v0.7.0

func (c CtrlFlow[B, C]) ToX() AnyCtrlFlow

func (CtrlFlow[B, C]) ToXBreak added in v0.7.0

func (c CtrlFlow[B, C]) ToXBreak() CtrlFlow[any, C]

func (CtrlFlow[B, C]) ToXContinue added in v0.7.0

func (c CtrlFlow[B, C]) ToXContinue() CtrlFlow[B, any]

func (CtrlFlow[B, C]) UnwrapBreak added in v0.7.0

func (c CtrlFlow[B, C]) UnwrapBreak() B

UnwrapBreak returns the inner value of a `Break` variant.

Panics if the variant is not a `Break`.

func (CtrlFlow[B, C]) UnwrapContinue added in v0.7.0

func (c CtrlFlow[B, C]) UnwrapContinue() C

UnwrapContinue returns the inner value of a `Continue` variant.

Panics if the variant is not a `Continue`.

func (CtrlFlow[B, C]) XMap added in v0.7.0

func (c CtrlFlow[B, C]) XMap(f func(B) any, g func(C) any) CtrlFlow[any, any]

XMap maps both `Break` and `Continue` values by applying functions to the break and continue values in case they exist.

func (CtrlFlow[B, C]) XMapBreak added in v0.7.0

func (c CtrlFlow[B, C]) XMapBreak(f func(B) any) CtrlFlow[any, C]

XMapBreak maps `Break` value by applying a function to the break value in case it exists.

func (CtrlFlow[B, C]) XMapContinue added in v0.7.0

func (c CtrlFlow[B, C]) XMapContinue(f func(C) any) CtrlFlow[B, any]

XMapContinue maps `Continue` value by applying a function to the continue value in case it exists.

type DeIterable added in v0.7.0

type DeIterable[T any] interface {
	Iterable[T]
	SizeIterable[T]
	NextBack() Option[T]
}

type DictEntry added in v1.4.3

type DictEntry[K comparable, V any] struct {
	Key   K
	Value V
}

DictEntry is a key-value entry of map.

type Digit added in v1.1.2

type Digit interface {
	Integer | ~float32 | ~float64
}

type EnumResult added in v0.7.0

type EnumResult[T any, E any] struct {
	// contains filtered or unexported fields
}

EnumResult represents a success (T) or failure (E) enumeration.

func EnumErr added in v0.7.0

func EnumErr[T any, E any](err E) EnumResult[T, E]

EnumErr wraps a failure result enumeration.

func EnumOk added in v0.7.0

func EnumOk[T any, E any](ok T) EnumResult[T, E]

EnumOk wraps a successful result enumeration.

func (EnumResult[T, E]) And added in v0.7.0

func (r EnumResult[T, E]) And(res EnumResult[T, E]) EnumResult[T, E]

And returns res if the result is T, otherwise returns the E of self.

func (EnumResult[T, E]) AndThen added in v0.7.0

func (r EnumResult[T, E]) AndThen(op func(T) EnumResult[T, E]) EnumResult[T, E]

AndThen calls op if the result is T, otherwise returns the E of self. This function can be used for control flow based on EnumResult values.

func (EnumResult[T, E]) AsPtr added in v1.5.2

func (r EnumResult[T, E]) AsPtr() *T

AsPtr returns its pointer or nil.

func (EnumResult[T, E]) CtrlFlow added in v0.7.0

func (r EnumResult[T, E]) CtrlFlow() CtrlFlow[E, T]

CtrlFlow returns the `CtrlFlow[E, T]`.

func (EnumResult[T, E]) Err added in v0.7.0

func (r EnumResult[T, E]) Err() Option[E]

Err returns E value `Option[E]`.

func (EnumResult[T, E]) Errable added in v0.7.0

func (r EnumResult[T, E]) Errable() Errable[E]

Errable converts from `EnumResult[T,E]` to `Errable[E]`.

func (EnumResult[T, E]) Expect added in v0.7.0

func (r EnumResult[T, E]) Expect(msg string) T

Expect returns the contained T value. Panics if the value is an E, with a panic message including the passed message, and the content of the E.

func (EnumResult[T, E]) ExpectErr added in v0.7.0

func (r EnumResult[T, E]) ExpectErr(msg string) E

ExpectErr returns the contained E. Panics if the value is not an E, with a panic message including the passed message, and the content of the T.

func (EnumResult[T, E]) Inspect added in v0.7.0

func (r EnumResult[T, E]) Inspect(f func(T)) EnumResult[T, E]

Inspect calls the provided closure with a reference to the contained value (if no E).

func (EnumResult[T, E]) InspectErr added in v0.7.0

func (r EnumResult[T, E]) InspectErr(f func(E)) EnumResult[T, E]

InspectErr calls the provided closure with a reference to the contained E (if E).

func (EnumResult[T, E]) IsErr added in v0.7.0

func (r EnumResult[T, E]) IsErr() bool

IsErr returns true if the result is E.

func (EnumResult[T, E]) IsErrAnd added in v0.7.0

func (r EnumResult[T, E]) IsErrAnd(f func(E) bool) bool

IsErrAnd returns true if the result is E and the value inside it matches a predicate.

func (EnumResult[T, E]) IsOk added in v0.7.0

func (r EnumResult[T, E]) IsOk() bool

IsOk returns true if the result is ok.

func (EnumResult[T, E]) IsOkAnd added in v0.7.0

func (r EnumResult[T, E]) IsOkAnd(f func(T) bool) bool

IsOkAnd returns true if the result is Ok and the value inside it matches a predicate.

func (*EnumResult[T, E]) IsValid added in v1.4.0

func (r *EnumResult[T, E]) IsValid() bool

IsValid returns true if the object is initialized.

func (EnumResult[T, E]) Map added in v0.7.0

func (r EnumResult[T, E]) Map(f func(T) T) EnumResult[T, E]

Map maps a EnumResult[T,E] to EnumResult[T,E] by applying a function to a contained T value, leaving an E untouched. This function can be used to compose the results of two functions.

func (EnumResult[T, E]) MapErr added in v0.7.0

func (r EnumResult[T, E]) MapErr(op func(E) E) EnumResult[T, E]

MapErr maps a EnumResult[T,E] to EnumResult[T,E] by applying a function to a contained E, leaving an T value untouched. This function can be used to pass through a successful result while handling an error.

func (EnumResult[T, E]) MapOr added in v0.7.0

func (r EnumResult[T, E]) MapOr(defaultOk T, f func(T) T) T

MapOr returns the provided default (if E), or applies a function to the contained value (if no E), Arguments passed to map_or are eagerly evaluated; if you are passing the result of a function call, it is recommended to use MapOrElse, which is lazily evaluated.

func (EnumResult[T, E]) MapOrElse added in v0.7.0

func (r EnumResult[T, E]) MapOrElse(defaultFn func(E) T, f func(T) T) T

MapOrElse maps a EnumResult[T,E] to T by applying fallback function default to a contained E, or function f to a contained T value. This function can be used to unpack a successful result while handling an E.

func (EnumResult[T, E]) MarshalJSON added in v0.7.0

func (r EnumResult[T, E]) MarshalJSON() ([]byte, error)

func (EnumResult[T, E]) Next added in v0.7.0

func (r EnumResult[T, E]) Next() Option[T]

func (EnumResult[T, E]) NextBack added in v0.7.0

func (r EnumResult[T, E]) NextBack() Option[T]

func (EnumResult[T, E]) Ok added in v0.7.0

func (r EnumResult[T, E]) Ok() Option[T]

Ok converts from `Result[T,E]` to `Option[T]`.

func (EnumResult[T, E]) Or added in v0.7.0

func (r EnumResult[T, E]) Or(res EnumResult[T, E]) EnumResult[T, E]

Or returns res if the result is E, otherwise returns the T value of r. Arguments passed to or are eagerly evaluated; if you are passing the result of a function call, it is recommended to use OrElse, which is lazily evaluated.

func (EnumResult[T, E]) OrElse added in v0.7.0

func (r EnumResult[T, E]) OrElse(op func(E) EnumResult[T, E]) EnumResult[T, E]

OrElse calls op if the result is E, otherwise returns the T value of self. This function can be used for control flow based on result values.

func (EnumResult[T, E]) Remaining added in v0.7.0

func (r EnumResult[T, E]) Remaining() uint

func (EnumResult[T, E]) Result added in v0.7.0

func (r EnumResult[T, E]) Result() Result[T]

Result converts from `EnumResult[T,E]` to `Result[T]`.

func (EnumResult[T, E]) Split added in v1.4.4

func (r EnumResult[T, E]) Split() (T, E)

Split returns the tuple (T, E).

func (EnumResult[T, E]) String added in v0.7.0

func (r EnumResult[T, E]) String() string

String returns the string representation.

func (EnumResult[T, E]) ToX added in v0.7.0

func (r EnumResult[T, E]) ToX() EnumResult[any, any]

ToX converts from `EnumResult[T,E]` to EnumResult[any,any]. nolint:gosimple

func (EnumResult[T, E]) ToXErr added in v0.7.0

func (r EnumResult[T, E]) ToXErr() EnumResult[T, any]

ToXErr converts from `EnumResult[T,E]` to EnumResult[T,any]. nolint:gosimple

func (EnumResult[T, E]) ToXOk added in v0.7.0

func (r EnumResult[T, E]) ToXOk() EnumResult[any, E]

ToXOk converts from `EnumResult[T,E]` to EnumResult[any,E]. nolint:gosimple

func (*EnumResult[T, E]) UnmarshalJSON added in v0.7.0

func (r *EnumResult[T, E]) UnmarshalJSON(b []byte) error

func (EnumResult[T, E]) Unwrap added in v0.7.0

func (r EnumResult[T, E]) Unwrap() T

Unwrap returns the contained T value. Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the E case explicitly, or call UnwrapOr or UnwrapOrElse.

func (EnumResult[T, E]) UnwrapErr added in v0.7.0

func (r EnumResult[T, E]) UnwrapErr() E

UnwrapErr returns the contained E. Panics if the value is not an E, with a custom panic message provided by the T's value.

func (EnumResult[T, E]) UnwrapOr added in v0.7.0

func (r EnumResult[T, E]) UnwrapOr(defaultT T) T

UnwrapOr returns the contained T value or a provided default. Arguments passed to UnwrapOr are eagerly evaluated; if you are passing the result of a function call, it is recommended to use UnwrapOrElse, which is lazily evaluated.

func (EnumResult[T, E]) UnwrapOrDefault added in v1.4.0

func (r EnumResult[T, E]) UnwrapOrDefault() T

UnwrapOrDefault returns the contained T or a non-nil-pointer zero T.

func (EnumResult[T, E]) UnwrapOrElse added in v0.7.0

func (r EnumResult[T, E]) UnwrapOrElse(defaultFn func(E) T) T

UnwrapOrElse returns the contained T value or computes it from a closure.

func (EnumResult[T, E]) UnwrapOrThrow added in v1.4.2

func (r EnumResult[T, E]) UnwrapOrThrow() T

UnwrapOrThrow returns the contained T or panic returns E (panicValue[*E]). NOTE:

If there is an E, that panic should be caught with CatchEnumResult[U, E]

func (EnumResult[T, E]) XAnd added in v0.7.0

func (r EnumResult[T, E]) XAnd(res EnumResult[any, E]) EnumResult[any, E]

XAnd returns res if the result is T, otherwise returns the E of self.

func (EnumResult[T, E]) XAndThen added in v0.7.0

func (r EnumResult[T, E]) XAndThen(op func(T) EnumResult[any, E]) EnumResult[any, E]

XAndThen calls op if the result is ok, otherwise returns the E of self. This function can be used for control flow based on EnumResult values.

func (EnumResult[T, E]) XErr added in v1.0.0

func (r EnumResult[T, E]) XErr() Option[any]

XErr returns E value `Option[any]`.

func (EnumResult[T, E]) XMap added in v0.7.0

func (r EnumResult[T, E]) XMap(f func(T) any) EnumResult[any, E]

XMap maps a EnumResult[T,E] to EnumResult[any,E] by applying a function to a contained `any` value, leaving an E untouched. This function can be used to compose the results of two functions.

func (EnumResult[T, E]) XMapErr added in v0.7.0

func (r EnumResult[T, E]) XMapErr(op func(E) any) EnumResult[T, any]

XMapErr maps a EnumResult[T,E] to EnumResult[T,any] by applying a function to a contained `any`, leaving an T value untouched. This function can be used to pass through a successful result while handling an error.

func (EnumResult[T, E]) XMapOr added in v0.7.0

func (r EnumResult[T, E]) XMapOr(defaultOk any, f func(T) any) any

XMapOr returns the provided default (if E), or applies a function to the contained value (if no E), Arguments passed to map_or are eagerly evaluated; if you are passing the result of a function call, it is recommended to use MapOrElse, which is lazily evaluated.

func (EnumResult[T, E]) XMapOrElse added in v0.7.0

func (r EnumResult[T, E]) XMapOrElse(defaultFn func(E) any, f func(T) any) any

XMapOrElse maps a EnumResult[T,E] to `any` type by applying fallback function default to a contained E, or function f to a contained T value. This function can be used to unpack a successful result while handling an E.

func (EnumResult[T, E]) XOk added in v1.0.0

func (r EnumResult[T, E]) XOk() Option[any]

XOk converts from `Result[T,E]` to `Option[any]`.

func (EnumResult[T, E]) XOr added in v0.7.0

func (r EnumResult[T, E]) XOr(res EnumResult[T, any]) EnumResult[T, any]

XOr returns res if the result is E, otherwise returns the T value of r. Arguments passed to or are eagerly evaluated; if you are passing the result of a function call, it is recommended to use XOrElse, which is lazily evaluated.

func (EnumResult[T, E]) XOrElse added in v0.7.0

func (r EnumResult[T, E]) XOrElse(op func(E) EnumResult[T, any]) EnumResult[T, any]

XOrElse calls op if the result is E, otherwise returns the T value of self. This function can be used for control flow based on result values.

type ErrBox added in v1.2.2

type ErrBox struct {
	// contains filtered or unexported fields
}

ErrBox is a wrapper for any error type.

func ToErrBox added in v1.2.2

func ToErrBox(val any) *ErrBox

ToErrBox wraps any error type.

func (*ErrBox) As added in v1.2.2

func (a *ErrBox) As(target any) bool

func (*ErrBox) Error added in v1.2.2

func (a *ErrBox) Error() string

Error returns the string representation.

func (*ErrBox) Is added in v1.2.2

func (a *ErrBox) Is(target error) bool

func (*ErrBox) Unwrap added in v1.2.2

func (a *ErrBox) Unwrap() error

Unwrap returns the inner error.

func (*ErrBox) Value added in v1.2.2

func (a *ErrBox) Value() any

Value returns the inner value.

type Errable added in v0.7.0

type Errable[E any] struct {
	// contains filtered or unexported fields
}

Errable is the type that indicates whether there is an error.

Example
package main

import (
	"fmt"

	"github.com/andeya/gust"
)

func main() {
	var hasErr = true
	var f = func() gust.Errable[int] {
		if hasErr {
			return gust.ToErrable(1)
		}
		return gust.NonErrable[int]()
	}
	var r = f()
	fmt.Println(r.IsErr())
	fmt.Println(r.UnwrapErr())
	fmt.Printf("%#v", r.ToError())
}
Output:

true
1
&gust.ErrBox{val:1}

func NonErrable added in v0.7.0

func NonErrable[E any]() Errable[E]

NonErrable returns no error object.

func ToErrable added in v0.7.0

func ToErrable[E any](errVal E) Errable[E]

ToErrable converts an error value (E) to `Errable[T]`.

func (Errable[E]) CtrlFlow added in v0.7.0

func (e Errable[E]) CtrlFlow() CtrlFlow[E, Void]

CtrlFlow returns the `CtrlFlow[E, Void]`.

func (Errable[E]) EnumResult added in v0.7.0

func (e Errable[E]) EnumResult() EnumResult[Void, E]

func (Errable[E]) Inspect added in v1.2.2

func (e Errable[E]) Inspect(f func()) Errable[E]

func (Errable[E]) InspectErr added in v1.2.2

func (e Errable[E]) InspectErr(f func(err E)) Errable[E]

func (Errable[E]) IsErr added in v0.7.0

func (e Errable[E]) IsErr() bool

func (Errable[E]) IsOk added in v0.8.0

func (e Errable[E]) IsOk() bool

func (Errable[E]) Option added in v0.7.0

func (e Errable[E]) Option() Option[E]

func (Errable[E]) Result added in v0.7.0

func (e Errable[E]) Result() Result[Void]

func (Errable[E]) ToError added in v0.7.0

func (e Errable[E]) ToError() error

func (Errable[E]) TryPanic added in v1.2.1

func (e Errable[E]) TryPanic()

TryPanic panics if the errVal is not nil.

func (Errable[E]) TryThrow added in v1.4.3

func (e Errable[E]) TryThrow()

TryThrow panic returns E (panicValue[*E]) if the errVal is not nil. NOTE:

If there is an E, that panic should be caught with CatchErrable[E] or CatchEnumResult[U, E].

func (Errable[E]) UnwrapErr added in v0.7.0

func (e Errable[E]) UnwrapErr() E

func (Errable[E]) UnwrapErrOr added in v0.7.0

func (e Errable[E]) UnwrapErrOr(def E) E

type Integer added in v1.1.2

type Integer interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}

type Iterable added in v0.7.0

type Iterable[T any] interface {
	Next() Option[T]
}

type IterableCount added in v0.7.0

type IterableCount interface {
	Count() uint
}

type IterableSizeHint added in v0.7.0

type IterableSizeHint interface {
	SizeHint() (uint, Option[uint])
}

type LazyValue added in v1.5.1

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

LazyValue a value that can be lazily initialized once and read concurrently.

func NewLazyValue added in v1.5.2

func NewLazyValue[T any]() *LazyValue[T]

NewLazyValue new empty LazyValue.

func NewLazyValueWithFunc added in v1.5.2

func NewLazyValueWithFunc[T any](onceInit func() Result[T]) *LazyValue[T]

NewLazyValueWithFunc new LazyValue with initialization function.

func NewLazyValueWithValue added in v1.5.2

func NewLazyValueWithValue[T any](v T) *LazyValue[T]

NewLazyValueWithValue new LazyValue with initialization value.

func NewLazyValueWithZero added in v1.5.2

func NewLazyValueWithZero[T any]() *LazyValue[T]

NewLazyValueWithZero new LazyValue with zero.

func (*LazyValue[T]) GetPtr added in v1.5.1

func (o *LazyValue[T]) GetPtr() *T

GetPtr returns its pointer or nil.

func (*LazyValue[T]) IsInitialized added in v1.5.1

func (o *LazyValue[T]) IsInitialized() bool

IsInitialized determine whether it is initialized.

func (*LazyValue[T]) SetInitFunc added in v1.5.2

func (o *LazyValue[T]) SetInitFunc(onceInit func() Result[T]) *LazyValue[T]

SetInitFunc set initialization function. NOTE: onceInit can not be nil

func (*LazyValue[T]) SetInitValue added in v1.5.2

func (o *LazyValue[T]) SetInitValue(v T) *LazyValue[T]

SetInitValue set the initialization value.

func (*LazyValue[T]) SetInitZero added in v1.5.2

func (o *LazyValue[T]) SetInitZero() *LazyValue[T]

SetInitZero set the zero value for initialization.

func (*LazyValue[T]) TryGetValue added in v1.5.1

func (o *LazyValue[T]) TryGetValue() Result[T]

TryGetValue concurrency-safe get the Result[T].

func (*LazyValue[T]) Zero added in v1.5.2

func (*LazyValue[T]) Zero() T

Zero creates a zero T.

type Mutex added in v1.2.2

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

Mutex is a better generic-type wrapper for `sync.Mutex` that holds a value. A Mutex is a mutual exclusion lock. The zero value for a Mutex is an unlocked mutex.

A Mutex must not be copied after first use.

In the terminology of the Go memory model, the n'th call to Unlock “synchronizes before” the m'th call to Lock for any n < m. A successful call to TryLock is equivalent to a call to Lock. A failed call to TryLock does not establish any “synchronizes before” relation at all.

func NewMutex added in v1.2.2

func NewMutex[T any](data T) *Mutex[T]

NewMutex returns a new *Mutex.

func (*Mutex[T]) Lock added in v1.2.2

func (m *Mutex[T]) Lock() T

Lock locks m. If the lock is already in use, the calling goroutine blocks until the mutex is available.

func (*Mutex[T]) LockScope added in v1.5.0

func (m *Mutex[T]) LockScope(f func(old T) (new T))

LockScope securely read and write the data in the Mutex[T].

func (*Mutex[T]) TryLock added in v1.2.2

func (m *Mutex[T]) TryLock() Option[T]

TryLock tries to lock m and reports whether it succeeded.

Note that while correct uses of TryLock do exist, they are rare, and use of TryLock is often a sign of a deeper problem in a particular use of mutexes.

func (*Mutex[T]) TryLockScope added in v1.5.0

func (m *Mutex[T]) TryLockScope(f func(old T) (new T))

TryLockScope tries to securely read and write the data in the Mutex[T].

func (*Mutex[T]) Unlock added in v1.2.2

func (m *Mutex[T]) Unlock(newData ...T)

Unlock unlocks m. It is a run-time error if m is not locked on entry to Unlock.

A locked Mutex is not associated with a particular goroutine. It is allowed for one goroutine to lock a Mutex and then arrange for another goroutine to unlock it.

type Option

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

Option can be used to avoid `(T, bool)` and `if *U != nil`, represents an optional value:

every [`Option`] is either [`Some`](which is non-none T), or [`None`](which is none).
Example
package main

import (
	"fmt"
	"strconv"

	"github.com/andeya/gust"
	"github.com/andeya/gust/opt"
)

func main() {
	type A struct {
		X int
	}
	var a = gust.Some(A{X: 1})
	fmt.Println(a.IsSome(), a.IsNone())

	var b = gust.None[A]()
	fmt.Println(b.IsSome(), b.IsNone())

	var x = b.UnwrapOr(A{X: 2})
	fmt.Println(x)

	var c *A
	fmt.Println(gust.PtrOpt(c).IsNone())
	fmt.Println(gust.ElemOpt(c).IsNone())
	c = new(A)
	fmt.Println(gust.PtrOpt(c).IsNone())
	fmt.Println(gust.ElemOpt(c).IsNone())

	type B struct {
		Y string
	}
	var d = opt.Map(a, func(t A) B {
		return B{
			Y: strconv.Itoa(t.X),
		}
	})
	fmt.Println(d)

}
Output:

true false
false true
{2}
true
true
false
false
Some({1})

func AssertOpt added in v1.4.0

func AssertOpt[T any](i any) Option[T]

AssertOpt wraps a value as an Option.

func BoolAssertOpt added in v1.4.0

func BoolAssertOpt[T any](i any, ok bool) Option[T]

BoolAssertOpt wraps a value as an Option.

func BoolOpt added in v1.0.0

func BoolOpt[T any](val T, ok bool) Option[T]

BoolOpt wraps a value as an Option. NOTE:

`ok=true` is wrapped as Some,
and `ok=false` is wrapped as None.

func ElemOpt added in v1.2.2

func ElemOpt[T any](ptr *T) Option[T]

ElemOpt wraps a value from pointer. NOTE:

`non-nil pointer` is wrapped as Some,
and `nil pointer` is wrapped as None.

func None

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

None returns a none. NOTE:

Option[T].IsNone() returns true,
and Option[T].IsSome() returns false.

func PtrOpt added in v1.0.0

func PtrOpt[U any, T *U](ptr T) Option[T]

PtrOpt wraps a pointer value. NOTE:

`non-nil pointer` is wrapped as Some,
and `nil pointer` is wrapped as None.

func Some

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

Some wraps a non-none value. NOTE:

Option[T].IsSome() returns true.
and Option[T].IsNone() returns false.

func ZeroOpt added in v1.0.0

func ZeroOpt[T comparable](val T) Option[T]

ZeroOpt wraps a value as an Option. NOTE:

`non-zero T` is wrapped as Some,
and `zero T` is wrapped as None.

func (Option[T]) And

func (o Option[T]) And(optb Option[T]) Option[T]

And returns [`None`] if the option is [`None`], otherwise returns `optb`.

func (Option[T]) AndThen

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

AndThen returns [`None`] if the option is [`None`], otherwise calls `f` with the

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

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

AsPtr returns its pointer or nil.

func (Option[T]) CtrlFlow added in v0.7.0

func (o Option[T]) CtrlFlow() CtrlFlow[Void, T]

CtrlFlow returns the `CtrlFlow[Void, T]`.

func (Option[T]) EnumOkOr added in v0.7.0

func (o Option[T]) EnumOkOr(err any) EnumResult[T, any]

EnumOkOr transforms the `Option[T]` into a [`EnumResult[T,any]`], mapping [`Some(v)`] to [`EnumOk(v)`] and [`None`] to [`EnumErr(err)`].

func (Option[T]) EnumOkOrElse added in v0.7.0

func (o Option[T]) EnumOkOrElse(errFn func() any) EnumResult[T, any]

EnumOkOrElse transforms the `Option[T]` into a [`EnumResult[T,any]`], mapping [`Some(v)`] to [`EnumOk(v)`] and [`None`] to [`EnumErr(errFn())`].

func (Option[T]) Expect

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

Expect returns the contained [`Some`] value. Panics if the value is none with a custom panic message provided by `msg`.

func (Option[T]) Filter

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

Filter returns [`None`] if the option is [`None`], otherwise calls `predicate` with the wrapped value and returns.

func (*Option[T]) GetOrInsert

func (o *Option[T]) GetOrInsert(some T) *T

GetOrInsert inserts `value` into the option if it is [`None`], then returns the contained value pointer.

func (*Option[T]) GetOrInsertDefault added in v1.4.3

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

GetOrInsertDefault inserts default value into the option if it is [`None`], then returns the contained value pointer.

func (*Option[T]) GetOrInsertWith

func (o *Option[T]) GetOrInsertWith(f func() T) *T

GetOrInsertWith inserts a value computed from `f` into the option if it is [`None`], then returns the contained value.

func (*Option[T]) Insert

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

Insert inserts `value` into the option, then returns its pointer.

func (Option[T]) Inspect

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

Inspect calls the provided closure with a reference to the contained value (if it has value).

Example
package main

import (
	"fmt"

	"github.com/andeya/gust"
)

func main() {
	// prints "got: 3"
	_ = gust.Some(3).Inspect(func(x int) {
		fmt.Println("got:", x)
	})

	// prints nothing
	_ = gust.None[int]().Inspect(func(x int) {
		fmt.Println("got:", x)
	})

}
Output:

got: 3

func (Option[T]) InspectNone

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

InspectNone calls the provided closure (if it is none).

func (Option[T]) IsNone

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

IsNone returns `true` if the option is none.

func (Option[T]) IsSome

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

IsSome returns `true` if the option has value.

func (Option[T]) IsSomeAnd

func (o Option[T]) IsSomeAnd(f func(T) bool) bool

IsSomeAnd returns `true` if the option has value and the value inside it matches a predicate.

func (Option[T]) Map

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

Map maps an `Option[T]` to `Option[T]` by applying a function to a contained value.

func (Option[T]) MapOr

func (o Option[T]) MapOr(defaultSome T, f func(T) T) T

MapOr returns the provided default value (if none), or applies a function to the contained value (if any).

func (Option[T]) MapOrElse

func (o Option[T]) MapOrElse(defaultFn func() T, f func(T) T) T

MapOrElse computes a default function value (if none), or applies a different function to the contained value (if any).

func (Option[T]) MarshalJSON added in v0.6.0

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

func (Option[T]) Next added in v0.7.0

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

func (Option[T]) NextBack added in v0.7.0

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

func (Option[T]) OkOr

func (o Option[T]) OkOr(err any) Result[T]

OkOr transforms the `Option[T]` into a [`Result[T]`], mapping [`Some(v)`] to [`Ok(v)`] and [`None`] to [`Err(err)`].

func (Option[T]) OkOrElse

func (o Option[T]) OkOrElse(errFn func() any) Result[T]

OkOrElse transforms the `Option[T]` into a [`Result[T]`], mapping [`Some(v)`] to [`Ok(v)`] and [`None`] to [`Err(errFn())`].

func (Option[T]) Or

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

Or returns the option if it contains a value, otherwise returns `optb`.

func (Option[T]) OrElse

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

OrElse returns the option if it contains a value, otherwise calls `f` and returns the result.

func (Option[T]) Remaining added in v0.7.0

func (o Option[T]) Remaining() uint

func (*Option[T]) Replace

func (o *Option[T]) Replace(some T) (old Option[T])

Replace replaces the actual value in the option by the value given in parameter, returning the old value if present, leaving a [`Some`] in its place without deinitializing either one.

func (Option[T]) Split added in v1.4.4

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

Split returns the tuple (T, bool).

func (Option[T]) String

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

String returns the string representation.

func (Option[T]) Take added in v0.7.0

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

Take takes the value out of the option, leaving a [`None`] in its place.

func (Option[T]) ToErrable added in v0.7.0

func (o Option[T]) ToErrable() Errable[T]

ToErrable converts from `Option[T]` to `Errable[T]`.

func (Option[T]) ToX added in v0.7.0

func (o Option[T]) ToX() Option[any]

ToX converts to `Option[any]`.

func (*Option[T]) UnmarshalJSON added in v0.6.0

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

func (Option[T]) Unwrap

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

Unwrap returns the contained value. Panics if the value is none.

func (Option[T]) UnwrapOr

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

UnwrapOr returns the contained value or a provided fallback value.

func (Option[T]) UnwrapOrDefault added in v1.3.3

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

UnwrapOrDefault returns the contained value or a non-nil-pointer zero value.

func (Option[T]) UnwrapOrElse

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

UnwrapOrElse returns the contained value or computes it from a closure.

func (Option[T]) UnwrapUnchecked

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

UnwrapUnchecked returns the contained value.

func (Option[T]) XAnd added in v0.7.0

func (o Option[T]) XAnd(optb Option[any]) Option[any]

XAnd returns [`None`] if the option is [`None`], otherwise returns `optb`.

func (Option[T]) XAndThen added in v0.7.0

func (o Option[T]) XAndThen(f func(T) Option[any]) Option[any]

XAndThen returns [`None`] if the option is [`None`], otherwise calls `f` with the

func (Option[T]) XEnumOkOr added in v1.0.0

func (o Option[T]) XEnumOkOr(err any) EnumResult[any, any]

XEnumOkOr transforms the `Option[T]` into a [`EnumResult[any,any]`], mapping [`Some(v)`] to [`EnumOk(v)`] and [`None`] to [`EnumErr(err)`].

func (Option[T]) XEnumOkOrElse added in v1.0.0

func (o Option[T]) XEnumOkOrElse(errFn func() any) EnumResult[any, any]

XEnumOkOrElse transforms the `Option[T]` into a [`EnumResult[any,any]`], mapping [`Some(v)`] to [`EnumOk(v)`] and [`None`] to [`EnumErr(errFn())`].

func (Option[T]) XMap added in v0.7.0

func (o Option[T]) XMap(f func(T) any) Option[any]

XMap maps an `Option[T]` to `Option[any]` by applying a function to a contained value.

func (Option[T]) XMapOr added in v0.7.0

func (o Option[T]) XMapOr(defaultSome any, f func(T) any) any

XMapOr returns the provided default value (if none), or applies a function to the contained value (if any).

func (Option[T]) XMapOrElse added in v0.7.0

func (o Option[T]) XMapOrElse(defaultFn func() any, f func(T) any) any

XMapOrElse computes a default function value (if none), or applies a different function to the contained value (if any).

func (Option[T]) XOkOr added in v1.0.0

func (o Option[T]) XOkOr(err any) Result[any]

XOkOr transforms the `Option[T]` into a [`Result[any]`], mapping [`Some(v)`] to [`Ok(v)`] and [`None`] to [`Err(err)`].

func (Option[T]) XOkOrElse added in v1.0.0

func (o Option[T]) XOkOrElse(errFn func() any) Result[any]

XOkOrElse transforms the `Option[T]` into a [`Result[any]`], mapping [`Some(v)`] to [`Ok(v)`] and [`None`] to [`Err(errFn())`].

func (Option[T]) Xor added in v0.7.0

func (o Option[T]) Xor(optb Option[T]) Option[T]

Xor [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].

type Ord added in v1.1.2

type Ord interface {
	Digit | ~string | ~uintptr
}

type Ordering added in v1.1.2

type Ordering struct {
	// contains filtered or unexported fields
}

func Compare added in v1.1.2

func Compare[T Ord](a, b T) Ordering

func Equal added in v1.1.2

func Equal() Ordering

func Greater added in v1.1.2

func Greater() Ordering

func Less added in v1.1.2

func Less() Ordering

func (Ordering) Is added in v1.1.2

func (o Ordering) Is(ord Ordering) bool

func (Ordering) IsEqual added in v1.1.2

func (o Ordering) IsEqual() bool

func (Ordering) IsGreater added in v1.1.2

func (o Ordering) IsGreater() bool

func (Ordering) IsLess added in v1.1.2

func (o Ordering) IsLess() bool

type Pair added in v0.7.0

type Pair[A any, B any] struct {
	A A
	B B
}

Pair is a pair of values.

type PureInteger added in v1.1.2

type PureInteger interface {
	int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64
}

type RWMutex added in v1.2.2

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

RWMutex is a better generic-type wrapper for `sync.RWMutex` that holds a value. A RWMutex is a reader/writer mutual exclusion lock. The lock can be held by an arbitrary number of readers or a single writer. The zero value for a RWMutex is an unlocked mutex.

A RWMutex must not be copied after first use.

If a goroutine holds a RWMutex for reading and another goroutine might call Lock, no goroutine should expect to be able to acquire a read lock until the initial read lock is released. In particular, this prohibits recursive read locking. This is to ensure that the lock eventually becomes available; a blocked Lock call excludes new readers from acquiring the lock.

In the terminology of the Go memory model, the n'th call to Unlock “synchronizes before” the m'th call to Lock for any n < m, just as for Mutex. For any call to RLock, there exists an n such that the n'th call to Unlock “synchronizes before” that call to RLock, and the corresponding call to RUnlock “synchronizes before” the n+1'th call to Lock.

func NewRWMutex added in v1.2.2

func NewRWMutex[T any](data T) *RWMutex[T]

NewRWMutex returns a new *RWMutex.

func (*RWMutex[T]) Lock added in v1.2.2

func (m *RWMutex[T]) Lock() T

Lock locks rw for writing. If the lock is already locked for reading or writing, Lock blocks until the lock is available.

func (*RWMutex[T]) LockScope added in v1.5.0

func (m *RWMutex[T]) LockScope(write func(old T) (new T))

LockScope securely read and write the data in the RWMutex[T].

func (*RWMutex[T]) RLock added in v1.2.2

func (m *RWMutex[T]) RLock() T

RLock locks rw for reading.

It should not be used for recursive read locking; a blocked Lock call excludes new readers from acquiring the lock. See the documentation on the RWMutex type.

func (*RWMutex[T]) RLockScope added in v1.5.0

func (m *RWMutex[T]) RLockScope(read func(T))

RLockScope securely read the data in the RWMutex[T].

func (*RWMutex[T]) RUnlock added in v1.2.2

func (m *RWMutex[T]) RUnlock()

RUnlock undoes a single RLock call; it does not affect other simultaneous readers. It is a run-time error if rw is not locked for reading on entry to RUnlock.

func (*RWMutex[T]) TryBest added in v1.5.0

func (m *RWMutex[T]) TryBest(readAndDo func(T) bool, swapWhenFalse func(old T) (new Option[T]))

TryBest tries to read and do the data in the RWMutex[T] safely, swapping the data when readAndDo returns false and then trying to do again.

func (*RWMutex[T]) TryLock added in v1.2.2

func (m *RWMutex[T]) TryLock() Option[T]

TryLock tries to lock rw for writing and reports whether it succeeded.

Note that while correct uses of TryLock do exist, they are rare, and use of TryLock is often a sign of a deeper problem

func (*RWMutex[T]) TryLockScope added in v1.5.0

func (m *RWMutex[T]) TryLockScope(write func(old T) (new T))

TryLockScope tries to securely read and write the data in the RWMutex[T].

func (*RWMutex[T]) TryRLock added in v1.2.2

func (m *RWMutex[T]) TryRLock() Option[T]

TryRLock tries to lock rw for reading and reports whether it succeeded.

Note that while correct uses of TryRLock do exist, they are rare, and use of TryRLock is often a sign of a deeper problem in a particular use of mutexes.

func (*RWMutex[T]) TryRLockScope added in v1.5.0

func (m *RWMutex[T]) TryRLockScope(read func(T))

TryRLockScope tries to securely read the data in the RWMutex[T].

func (*RWMutex[T]) Unlock added in v1.2.2

func (m *RWMutex[T]) Unlock(newData ...T)

Unlock unlocks rw for writing. It is a run-time error if rw is not locked for writing on entry to Unlock.

As with Mutexes, a locked RWMutex is not associated with a particular goroutine. One goroutine may RLock (Lock) a RWMutex and then arrange for another goroutine to RUnlock (Unlock) it.

type Result

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

Result can be used to improve `func()(T,error)`, represents either success (T) or failure (error).

func Err

func Err[T any](err any) Result[T]

Err wraps a failure result.

func Ok

func Ok[T any](ok T) Result[T]

Ok wraps a successful result.

func Ret

func Ret[T any](some T, err error) Result[T]

Ret wraps a result.

func (Result[T]) And

func (r Result[T]) And(res Result[T]) Result[T]

And returns res if the result is Ok, otherwise returns the error of self.

func (Result[T]) AndThen

func (r Result[T]) AndThen(op func(T) Result[T]) Result[T]

AndThen calls op if the result is Ok, otherwise returns the error of self. This function can be used for control flow based on Result values.

Example
package main

import (
	"fmt"

	"github.com/andeya/gust"
)

func main() {
	var divide = func(i, j float32) gust.Result[float32] {
		if j == 0 {
			return gust.Err[float32]("j can not be 0")
		}
		return gust.Ok(i / j)
	}
	var ret float32 = divide(1, 2).AndThen(func(i float32) gust.Result[float32] {
		return gust.Ok(i * 10)
	}).Unwrap()
	fmt.Println(ret)
}
Output:

5

func (Result[T]) AsPtr added in v1.5.2

func (r Result[T]) AsPtr() *T

AsPtr returns its pointer or nil.

func (Result[T]) ContainsErr

func (r Result[T]) ContainsErr(err any) bool

ContainsErr returns true if the result is an error containing the given value.

func (Result[T]) CtrlFlow added in v0.7.0

func (r Result[T]) CtrlFlow() CtrlFlow[error, T]

CtrlFlow returns the `CtrlFlow[error, T]`.

func (Result[T]) EnumResult added in v0.7.0

func (r Result[T]) EnumResult() EnumResult[T, error]

EnumResult returns the inner EnumResult[T, error].

func (Result[T]) Err

func (r Result[T]) Err() error

Err returns error.

func (Result[T]) ErrVal

func (r Result[T]) ErrVal() any

ErrVal returns error inner value.

func (Result[T]) Errable added in v0.7.0

func (r Result[T]) Errable() Errable[error]

Errable converts from `Result[T]` to `Errable[error]`.

func (Result[T]) Expect

func (r Result[T]) Expect(msg string) T

Expect returns the contained Ok value. Panics if the value is an error, with a panic message including the passed message, and the content of the error.

func (Result[T]) ExpectErr

func (r Result[T]) ExpectErr(msg string) error

ExpectErr returns the contained error. Panics if the value is not an error, with a panic message including the passed message, and the content of the [`Ok`].

func (Result[T]) Inspect

func (r Result[T]) Inspect(f func(T)) Result[T]

Inspect calls the provided closure with a reference to the contained value (if no error).

func (Result[T]) InspectErr

func (r Result[T]) InspectErr(f func(error)) Result[T]

InspectErr calls the provided closure with a reference to the contained error (if error).

func (Result[T]) IsErr

func (r Result[T]) IsErr() bool

IsErr returns true if the result is error.

func (Result[T]) IsErrAnd

func (r Result[T]) IsErrAnd(f func(error) bool) bool

IsErrAnd returns true if the result is error and the value inside it matches a predicate.

func (Result[T]) IsOk

func (r Result[T]) IsOk() bool

IsOk returns true if the result is Ok.

func (Result[T]) IsOkAnd

func (r Result[T]) IsOkAnd(f func(T) bool) bool

IsOkAnd returns true if the result is Ok and the value inside it matches a predicate.

func (*Result[T]) IsValid added in v1.4.0

func (r *Result[T]) IsValid() bool

IsValid returns true if the object is initialized.

func (Result[T]) Map

func (r Result[T]) Map(f func(T) T) Result[T]

Map maps a Result[T] to Result[T] by applying a function to a contained Ok value, leaving an error untouched. This function can be used to compose the results of two functions.

func (Result[T]) MapErr

func (r Result[T]) MapErr(op func(error) (newErr any)) Result[T]

MapErr maps a Result[T] to Result[T] by applying a function to a contained error, leaving an Ok value untouched. This function can be used to pass through a successful result while handling an error.

func (Result[T]) MapOr

func (r Result[T]) MapOr(defaultOk T, f func(T) T) T

MapOr returns the provided default (if error), or applies a function to the contained value (if no error), Arguments passed to map_or are eagerly evaluated; if you are passing the result of a function call, it is recommended to use MapOrElse, which is lazily evaluated.

func (Result[T]) MapOrElse

func (r Result[T]) MapOrElse(defaultFn func(error) T, f func(T) T) T

MapOrElse maps a Result[T] to T by applying fallback function default to a contained error, or function f to a contained Ok value. This function can be used to unpack a successful result while handling an error.

func (Result[T]) MarshalJSON added in v0.6.0

func (r Result[T]) MarshalJSON() ([]byte, error)

func (Result[T]) Next added in v0.7.0

func (r Result[T]) Next() Option[T]

func (Result[T]) NextBack added in v0.7.0

func (r Result[T]) NextBack() Option[T]

func (Result[T]) Ok

func (r Result[T]) Ok() Option[T]

Ok converts from `Result[T]` to `Option[T]`.

func (Result[T]) Or

func (r Result[T]) Or(res Result[T]) Result[T]

Or returns res if the result is Err, otherwise returns the Ok value of r. Arguments passed to or are eagerly evaluated; if you are passing the result of a function call, it is recommended to use OrElse, which is lazily evaluated.

func (Result[T]) OrElse

func (r Result[T]) OrElse(op func(error) Result[T]) Result[T]

OrElse calls op if the result is Err, otherwise returns the Ok value of self. This function can be used for control flow based on result values.

func (Result[T]) Remaining added in v0.7.0

func (r Result[T]) Remaining() uint

func (Result[T]) Split added in v1.4.4

func (r Result[T]) Split() (T, error)

Split returns the tuple (T, error).

func (Result[T]) String

func (r Result[T]) String() string

String returns the string representation.

func (Result[T]) ToX added in v0.7.0

func (r Result[T]) ToX() Result[any]

ToX converts from `Result[T]` to Result[any].

func (*Result[T]) UnmarshalJSON added in v0.6.0

func (r *Result[T]) UnmarshalJSON(b []byte) error

func (Result[T]) Unwrap

func (r Result[T]) Unwrap() T

Unwrap returns the contained Ok value. Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the error case explicitly, or call UnwrapOr or UnwrapOrElse.

func (Result[T]) UnwrapErr

func (r Result[T]) UnwrapErr() error

UnwrapErr returns the contained error. Panics if the value is not an error, with a custom panic message provided by the [`Ok`]'s value.

func (Result[T]) UnwrapOr

func (r Result[T]) UnwrapOr(defaultOk T) T

UnwrapOr returns the contained Ok value or a provided default. Arguments passed to UnwrapOr are eagerly evaluated; if you are passing the result of a function call, it is recommended to use UnwrapOrElse, which is lazily evaluated.

Example
package main

import (
	"fmt"
	"strconv"

	"github.com/andeya/gust"
)

func main() {
	const def int = 10

	// before
	i, err := strconv.Atoi("1")
	if err != nil {
		i = def
	}
	fmt.Println(i * 2)

	// now
	fmt.Println(gust.Ret(strconv.Atoi("1")).UnwrapOr(def) * 2)

}
Output:

2
2

func (Result[T]) UnwrapOrDefault added in v1.4.0

func (r Result[T]) UnwrapOrDefault() T

UnwrapOrDefault returns the contained T or a non-nil-pointer zero T.

func (Result[T]) UnwrapOrElse

func (r Result[T]) UnwrapOrElse(defaultFn func(error) T) T

UnwrapOrElse returns the contained Ok value or computes it from a closure.

func (Result[T]) UnwrapOrThrow added in v1.4.2

func (r Result[T]) UnwrapOrThrow() T

UnwrapOrThrow returns the contained T or panic returns error (panicValue[*any]). NOTE:

If there is an error, that panic should be caught with CatchResult[U]

func (Result[T]) XAnd added in v0.7.0

func (r Result[T]) XAnd(res Result[any]) Result[any]

XAnd returns res if the result is Ok, otherwise returns the error of self.

func (Result[T]) XAndThen added in v0.7.0

func (r Result[T]) XAndThen(op func(T) Result[any]) Result[any]

XAndThen calls op if the result is Ok, otherwise returns the error of self. This function can be used for control flow based on Result values.

func (Result[T]) XMap added in v0.7.0

func (r Result[T]) XMap(f func(T) any) Result[any]

XMap maps a Result[T] to Result[any] by applying a function to a contained Ok value, leaving an error untouched. This function can be used to compose the results of two functions.

func (Result[T]) XMapOr added in v0.7.0

func (r Result[T]) XMapOr(defaultOk any, f func(T) any) any

XMapOr returns the provided default (if error), or applies a function to the contained value (if no error), Arguments passed to map_or are eagerly evaluated; if you are passing the result of a function call, it is recommended to use MapOrElse, which is lazily evaluated.

func (Result[T]) XMapOrElse added in v0.7.0

func (r Result[T]) XMapOrElse(defaultFn func(error) any, f func(T) any) any

XMapOrElse maps a Result[T] to `any` by applying fallback function default to a contained error, or function f to a contained Ok value. This function can be used to unpack a successful result while handling an error.

func (Result[T]) XOk added in v1.0.0

func (r Result[T]) XOk() Option[any]

XOk converts from `Result[T]` to `Option[any]`.

type SigCtrlFlow added in v0.7.0

type SigCtrlFlow[T any] struct {
	CtrlFlow[T, T]
}

SigCtrlFlow is a placeholder for single type control flow statements.

func SigBreak added in v0.7.0

func SigBreak[T any](b T) SigCtrlFlow[T]

SigBreak returns a `SigCtrlFlow[T]` that tells the operation to break.

func SigContinue added in v0.7.0

func SigContinue[T any](c T) SigCtrlFlow[T]

SigContinue returns a `SigCtrlFlow[T]` that tells the operation to continue.

type SizeIterable added in v0.7.0

type SizeIterable[T any] interface {
	Remaining() uint
}

type SyncMap added in v1.4.0

type SyncMap[K any, V any] struct {
	// contains filtered or unexported fields
}

SyncMap is a better generic-type wrapper for `sync.Map`. A SyncMap is like a Go map[interface{}]interface{} but is safe for concurrent use by multiple goroutines without additional locking or coordination. Loads, stores, and deletes run in amortized constant time.

The SyncMap type is specialized. Most code should use a plain Go map instead, with separate locking or coordination, for better type safety and to make it easier to maintain other invariants along with the map content.

The SyncMap type is optimized for two common use cases: (1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys. In these two cases, use of a SyncMap may significantly reduce lock contention compared to a Go map paired with a separate Mutex or RWMutex.

The zero SyncMap is empty and ready for use. A SyncMap must not be copied after first use.

In the terminology of the Go memory model, SyncMap arranges that a write operation “synchronizes before” any read operation that observes the effect of the write, where read and write operations are defined as follows. Load, LoadAndDelete, LoadOrStore are read operations; Delete, LoadAndDelete, and Store are write operations; and LoadOrStore is a write operation when it returns loaded set to false.

func (*SyncMap[K, V]) Delete added in v1.4.0

func (m *SyncMap[K, V]) Delete(key K)

Delete deletes the value for a key.

func (*SyncMap[K, V]) Load added in v1.4.0

func (m *SyncMap[K, V]) Load(key K) Option[V]

Load returns the value stored in the map for a key.

func (*SyncMap[K, V]) LoadAndDelete added in v1.4.0

func (m *SyncMap[K, V]) LoadAndDelete(key K) (deletedValue Option[V])

LoadAndDelete deletes the value for a key, returning the previous value if any.

func (*SyncMap[K, V]) LoadOrStore added in v1.4.0

func (m *SyncMap[K, V]) LoadOrStore(key K, value V) (existingValue Option[V])

LoadOrStore returns the existing value for the key if present. Otherwise, it stores the given value, and returns None.

func (*SyncMap[K, V]) Range added in v1.4.0

func (m *SyncMap[K, V]) Range(f func(key K, value V) bool)

Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration.

Range does not necessarily correspond to any consistent snapshot of the SyncMap's contents: no key will be visited more than once, but if the value for any key is stored or deleted concurrently (including by f), Range may reflect any mapping for that key from any point during the Range call. Range does not block other methods on the receiver; even f itself may call any method on m.

Range may be O(N) with the number of elements in the map even if f returns false after a constant number of calls.

func (*SyncMap[K, V]) Store added in v1.4.0

func (m *SyncMap[K, V]) Store(key K, value V)

Store sets the value for a key.

type VecEntry added in v1.3.1

type VecEntry[T any] struct {
	Index int
	Elem  T
}

VecEntry is an index-element entry of slice or array.

type Void added in v0.7.0

type Void = *struct{}

Void is a type that represents the absence of a value.

Directories

Path Synopsis
Package dict is a package of generic-type functions for map.
Package dict is a package of generic-type functions for map.
Package digit is a package of generic-type functions for digit.
Package digit is a package of generic-type functions for digit.
Package iter is a package that provides a generic-type iterator.
Package iter is a package that provides a generic-type iterator.
Package valconv is a package that provides a generic-type value converter.
Package valconv is a package that provides a generic-type value converter.
Package vec is a package of generic-type functions for slices.
Package vec is a package of generic-type functions for slices.

Jump to

Keyboard shortcuts

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