Documentation
¶
Overview ¶
Package gust provides Rust-inspired error handling, optional values, and iteration utilities for Go. This file contains numeric type constraints for generic programming.
Package gust provides Rust-inspired error handling, optional values, and iteration utilities for Go. This file contains ordering types and comparison utilities.
Package gust provides Rust-inspired error handling, optional values, and iteration utilities for Go. This file contains common types and interfaces used throughout the package.
Package gust provides Rust-inspired error handling, optional values, and iteration utilities for Go. This file contains the Void type for representing the absence of a value.
Index ¶
- Constants
- func ToError(r VoidResult) error
- func UnwrapErrOr(r VoidResult, def error) error
- type AtomicValue
- type DictEntry
- type Digit
- type DoubleEndedIterable
- type ErrBox
- func (e *ErrBox) As(target any) bool
- func (e *ErrBox) GoString() string
- func (e *ErrBox) Is(target error) bool
- func (e *ErrBox) IsEmpty() bool
- func (e *ErrBox) String() string
- func (e *ErrBox) ToError() error
- func (e *ErrBox) Unwrap() error
- func (e *ErrBox) Value() any
- func (e *ErrBox) ValueOrDefault() any
- type Integer
- type Iterable
- type IterableCount
- type IterableSizeHint
- type LazyValue
- func (o *LazyValue[T]) GetPtr() *T
- func (o *LazyValue[T]) IsInitialized() bool
- func (o *LazyValue[T]) SetInitFunc(onceInit func() Result[T]) *LazyValue[T]
- func (o *LazyValue[T]) SetInitValue(v T) *LazyValue[T]
- func (o *LazyValue[T]) SetInitZero() *LazyValue[T]
- func (o *LazyValue[T]) TryGetValue() Result[T]
- func (*LazyValue[T]) Zero() T
- type Mutex
- type Option
- func AssertOpt[T any](i any) Option[T]
- func BoolAssertOpt[T any](i any, ok bool) Option[T]
- func BoolOpt[T any](value T, ok bool) Option[T]
- func ElemOpt[T any](ptr *T) Option[T]
- func None[T any]() Option[T]
- func PtrOpt[U any, T *U](ptr T) Option[T]
- func RetAnyOpt[T any](value any, err error) Option[any]
- func RetOpt[T any](value T, err error) Option[T]
- func Some[T any](value T) Option[T]
- func ZeroOpt[T comparable](value T) Option[T]
- func (o Option[T]) And(optb Option[T]) Option[T]
- func (o Option[T]) AndThen(f func(T) Option[T]) Option[T]
- func (o *Option[T]) AsPtr() *T
- func (o Option[T]) Expect(msg string) T
- func (o Option[T]) Filter(predicate func(T) bool) Option[T]
- func (o *Option[T]) GetOrInsert(some T) *T
- func (o *Option[T]) GetOrInsertDefault() *T
- func (o *Option[T]) GetOrInsertWith(f func() T) *T
- func (o *Option[T]) Insert(some T) *T
- func (o Option[T]) Inspect(f func(T)) Option[T]
- func (o Option[T]) InspectNone(f func()) Option[T]
- func (o Option[T]) IsNone() bool
- func (o Option[T]) IsSome() bool
- func (o Option[T]) IsSomeAnd(f func(T) bool) bool
- func (o Option[T]) Map(f func(T) T) Option[T]
- func (o Option[T]) MapOr(defaultSome T, f func(T) T) T
- func (o Option[T]) MapOrElse(defaultFn func() T, f func(T) T) T
- func (o Option[T]) MarshalJSON() ([]byte, error)
- func (o *Option[T]) Next() Option[T]
- func (o *Option[T]) NextBack() Option[T]
- func (o Option[T]) OkOr(err any) Result[T]
- func (o Option[T]) OkOrElse(errFn func() any) Result[T]
- func (o Option[T]) Or(optb Option[T]) Option[T]
- func (o Option[T]) OrElse(f func() Option[T]) Option[T]
- func (o Option[T]) Ref() *Option[T]
- func (o *Option[T]) Remaining() uint
- func (o *Option[T]) Replace(some T) (old Option[T])
- func (o Option[T]) Split() (T, bool)
- func (o Option[T]) String() string
- func (o *Option[T]) Take() Option[T]
- func (o Option[T]) ToResult() VoidResult
- func (o Option[T]) ToX() Option[any]
- func (o *Option[T]) UnmarshalJSON(b []byte) error
- func (o Option[T]) Unwrap() T
- func (o Option[T]) UnwrapOr(fallbackValue T) T
- func (o Option[T]) UnwrapOrDefault() T
- func (o Option[T]) UnwrapOrElse(defaultSome func() T) T
- func (r Option[T]) UnwrapOrThrow(err any) T
- func (o Option[T]) UnwrapUnchecked() T
- func (o Option[T]) XAnd(optb Option[any]) Option[any]
- func (o Option[T]) XAndThen(f func(T) Option[any]) Option[any]
- func (o Option[T]) XMap(f func(T) any) Option[any]
- func (o Option[T]) XMapOr(defaultSome any, f func(T) any) any
- func (o Option[T]) XMapOrElse(defaultFn func() any, f func(T) any) any
- func (o Option[T]) XOkOr(err any) Result[any]
- func (o Option[T]) XOkOrElse(errFn func() any) Result[any]
- func (o Option[T]) Xor(optb Option[T]) Option[T]
- type Ord
- type Ordering
- type Pair
- type PureInteger
- type RWMutex
- func (m *RWMutex[T]) Lock() T
- func (m *RWMutex[T]) LockScope(write func(old T) (new T))
- func (m *RWMutex[T]) RLock() T
- func (m *RWMutex[T]) RLockScope(read func(T))
- func (m *RWMutex[T]) RUnlock()
- func (m *RWMutex[T]) TryBest(readAndDo func(T) bool, swapWhenFalse func(old T) (new Option[T]))
- func (m *RWMutex[T]) TryLock() Option[T]
- func (m *RWMutex[T]) TryLockScope(write func(old T) (new T))
- func (m *RWMutex[T]) TryRLock() Option[T]
- func (m *RWMutex[T]) TryRLockScope(read func(T))
- func (m *RWMutex[T]) Unlock(newData ...T)
- type Result
- func (r Result[T]) And(r2 Result[T]) Result[T]
- func (r Result[T]) And2(v2 T, err2 error) Result[T]
- func (r Result[T]) AndThen(op func(T) Result[T]) Result[T]
- func (r Result[T]) AndThen2(op func(T) (T, error)) Result[T]
- func (r Result[T]) AsPtr() *T
- func (r *Result[T]) Catch()
- func (r Result[T]) ContainsErr(err any) bool
- func (r Result[T]) Err() error
- func (r Result[T]) ErrVal() any
- func (r Result[T]) Expect(msg string) T
- func (r Result[T]) ExpectErr(msg string) error
- func (r Result[T]) Flatten(err error) Result[T]
- func (r Result[T]) Inspect(f func(T)) Result[T]
- func (r Result[T]) InspectErr(f func(error)) Result[T]
- func (r Result[T]) IsErr() bool
- func (r Result[T]) IsErrAnd(f func(error) bool) bool
- func (r Result[T]) IsOk() bool
- func (r Result[T]) IsOkAnd(f func(T) bool) bool
- func (r *Result[T]) IsValid() bool
- func (r Result[T]) Map(f func(T) T) Result[T]
- func (r Result[T]) MapErr(op func(error) (newErr any)) Result[T]
- func (r Result[T]) MapOr(defaultOk T, f func(T) T) T
- func (r Result[T]) MapOrElse(defaultFn func(error) T, f func(T) T) T
- func (r Result[T]) MarshalJSON() ([]byte, error)
- func (r *Result[T]) Next() Option[T]
- func (r *Result[T]) NextBack() Option[T]
- func (r Result[T]) Ok() Option[T]
- func (r Result[T]) Or(r2 Result[T]) Result[T]
- func (r Result[T]) Or2(v2 T, err2 error) Result[T]
- func (r Result[T]) OrElse(op func(error) Result[T]) Result[T]
- func (r Result[T]) OrElse2(op func(error) (T, error)) Result[T]
- func (r Result[T]) Ref() *Result[T]
- func (r *Result[T]) Remaining() uint
- func (r Result[T]) Split() (T, error)
- func (r Result[T]) String() string
- func (r Result[T]) ToX() Result[any]
- func (r *Result[T]) UnmarshalJSON(b []byte) error
- func (r Result[T]) Unwrap() T
- func (r Result[T]) UnwrapErr() error
- func (r Result[T]) UnwrapOr(defaultOk T) T
- func (r Result[T]) UnwrapOrDefault() T
- func (r Result[T]) UnwrapOrElse(defaultFn func(error) T) T
- func (r Result[T]) UnwrapOrThrow() T
- func (r Result[T]) UnwrapUnchecked() T
- func (r Result[T]) XAnd(res Result[any]) Result[any]
- func (r Result[T]) XAnd2(v2 any, err2 error) Result[any]
- func (r Result[T]) XAndThen(op func(T) Result[any]) Result[any]
- func (r Result[T]) XAndThen2(op func(T) (any, error)) Result[any]
- func (r Result[T]) XMap(f func(T) any) Result[any]
- func (r Result[T]) XMapOr(defaultOk any, f func(T) any) any
- func (r Result[T]) XMapOrElse(defaultFn func(error) any, f func(T) any) any
- func (r Result[T]) XOk() Option[any]
- type SizeIterable
- type SyncMap
- func (m *SyncMap[K, V]) Delete(key K)
- func (m *SyncMap[K, V]) Load(key K) Option[V]
- func (m *SyncMap[K, V]) LoadAndDelete(key K) (deletedValue Option[V])
- func (m *SyncMap[K, V]) LoadOrStore(key K, value V) (existingValue Option[V])
- func (m *SyncMap[K, V]) Range(f func(key K, value V) bool)
- func (m *SyncMap[K, V]) Store(key K, value V)
- type VecEntry
- type Void
- type VoidResult
Examples ¶
Constants ¶
const ErrLazyValueWithoutInit = "*gust.LazyValue[T]: onceInit function is nil"
Variables ¶
This section is empty.
Functions ¶
func ToError ¶ added in v1.11.0
func ToError(r VoidResult) error
ToError converts VoidResult to a standard Go error. Returns nil if IsOk() is true, otherwise returns the error.
Example:
```go
var result gust.VoidResult = gust.RetVoid(err)
if err := gust.ToError(result); err != nil {
return err
}
```
func UnwrapErrOr ¶ added in v1.11.0
UnwrapErrOr returns the contained error value or a provided default for VoidResult.
Example:
```go
var result gust.VoidResult = gust.RetVoid(err)
err := gust.UnwrapErrOr(result, errors.New("default error"))
```
Types ¶
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 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
Digit represents numeric types including integers and floating-point numbers.
type DoubleEndedIterable ¶ added in v1.7.0
type DoubleEndedIterable[T any] interface { Iterable[T] SizeIterable[T] NextBack() Option[T] }
DoubleEndedIterable represents an iterable that can be iterated from both ends.
type ErrBox ¶ added in v1.2.2
type ErrBox struct {
// contains filtered or unexported fields
}
ErrBox is a wrapper for any error type. Use ToError() method to convert to error interface, or access ErrBox through Result.Err().
func (*ErrBox) As ¶ added in v1.2.2
As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true. Otherwise, it returns false.
func (*ErrBox) GoString ¶ added in v1.11.0
GoString returns the Go-syntax representation. This implements the fmt.GoStringer interface.
func (*ErrBox) IsEmpty ¶ added in v1.11.0
IsEmpty returns true if ErrBox is empty (nil receiver or nil val).
func (*ErrBox) String ¶ added in v1.11.0
String returns the string representation. This implements the fmt.Stringer interface.
func (*ErrBox) ToError ¶ added in v1.11.0
ToError converts ErrBox to error interface. Returns nil if the receiver is nil or val is nil. Returns a pointer to innerErrBox which implements the error interface.
Example:
```go
var eb gust.ErrBox = gust.BoxErr(errors.New("test"))
var err error = eb.ToError() // err is *innerErrBox implementing error
```
func (*ErrBox) ValueOrDefault ¶ added in v1.11.0
ValueOrDefault returns the inner value, or nil if ErrBox is nil or val is nil. This is useful when you want to safely extract a typed value from ErrBox.
type Integer ¶ added in v1.1.2
type Integer interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}
Integer represents integer types including type aliases.
type IterableCount ¶ added in v0.7.0
type IterableCount interface {
Count() uint
}
IterableCount represents an iterable that can count its elements.
type IterableSizeHint ¶ added in v0.7.0
IterableSizeHint represents an iterable that can provide size hints.
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
NewLazyValue new empty LazyValue.
func NewLazyValueWithFunc ¶ added in v1.5.2
NewLazyValueWithFunc new LazyValue with initialization function. The value will be computed lazily when TryGetValue() is called.
func NewLazyValueWithValue ¶ added in v1.5.2
NewLazyValueWithValue new LazyValue with initialization value. The value will be computed lazily when TryGetValue() is called.
func NewLazyValueWithZero ¶ added in v1.5.2
NewLazyValueWithZero new LazyValue with zero. The value will be computed lazily when TryGetValue() is called.
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
IsInitialized determine whether it is initialized.
func (*LazyValue[T]) SetInitFunc ¶ added in v1.5.2
SetInitFunc set initialization function. NOTE: onceInit can not be nil If the LazyValue already has an initialization function set (even if not initialized yet), this function will not override it.
func (*LazyValue[T]) SetInitValue ¶ added in v1.5.2
SetInitValue set the initialization value.
func (*LazyValue[T]) SetInitZero ¶ added in v1.5.2
SetInitZero set the zero value for initialization.
func (*LazyValue[T]) TryGetValue ¶ added in v1.5.1
TryGetValue concurrency-safe get the Result[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 (*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
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 BoolAssertOpt ¶ added in v1.4.0
BoolAssertOpt wraps a value as an Option. NOTE:
`ok=true` is wrapped as Some, and `ok=false` is wrapped as None.
func BoolOpt ¶ added in v1.0.0
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
ElemOpt wraps a value from pointer. NOTE:
`non-nil pointer` is wrapped as Some, and `nil pointer` is wrapped as None.
func None ¶
None returns a none. NOTE:
Option[T].IsNone() returns true, and Option[T].IsSome() returns false.
func PtrOpt ¶ added in v1.0.0
PtrOpt wraps a pointer value. NOTE:
`non-nil pointer` is wrapped as Some, and `nil pointer` is wrapped as None.
func RetAnyOpt ¶ added in v1.8.0
RetAnyOpt wraps a value as an `Option[any]`. NOTE:
`err != nil` or `value`==nil is wrapped as None, and `err == nil` and `value != nil` is wrapped as Some.
func RetOpt ¶ added in v1.8.0
RetOpt wraps a value as an `Option[T]`. NOTE:
`err != nil` is wrapped as None, and `err == nil` is wrapped as Some.
func Some ¶
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](value 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]) AndThen ¶
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]) Expect ¶
Expect returns the contained [`Some`] value. Panics if the value is none with a custom panic message provided by `msg`.
func (Option[T]) Filter ¶
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 ¶
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 ¶
InspectNone calls the provided closure (if it is none).
func (Option[T]) IsSomeAnd ¶
IsSomeAnd returns `true` if the option has value and the value inside it matches a predicate.
func (Option[T]) Map ¶
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
MarshalJSON implements the json.Marshaler interface.
func (*Option[T]) NextBack ¶ added in v0.7.0
NextBack returns the next element from the back of the iterator.
func (Option[T]) OkOr ¶
OkOr transforms the `Option[T]` into a [`Result[T]`], mapping [`Some(v)`] to [`Ok(v)`] and [`None`] to [`Err(err)`].
func (Option[T]) OkOrElse ¶
OkOrElse transforms the `Option[T]` into a [`Result[T]`], mapping [`Some(v)`] to [`Ok(v)`] and [`None`] to [`Err(errFn())`].
func (Option[T]) OrElse ¶
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
Remaining returns the number of remaining elements in the iterator.
func (*Option[T]) Replace ¶
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]) Take ¶ added in v0.7.0
Take takes the value out of the option, leaving a [`None`] in its place.
func (Option[T]) ToResult ¶ added in v1.11.0
func (o Option[T]) ToResult() VoidResult
ToResult converts from `Option[T]` to `VoidResult` (Result[Void]). If Option is Some, returns Err[Void] with the value wrapped in ErrBox. If Option is None, returns Ok[Void](nil).
Example:
```go
var opt gust.Option[string] = gust.Some("value")
var result gust.VoidResult = opt.ToResult()
```
func (*Option[T]) UnmarshalJSON ¶ added in v0.6.0
UnmarshalJSON implements the json.Unmarshaler interface.
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]) UnwrapOrThrow ¶ added in v1.5.3
UnwrapOrThrow returns the contained T or panic returns error (*ErrBox). NOTE:
If there is an error, that panic should be caught with `Result.Catch()`
func (Option[T]) UnwrapUnchecked ¶
func (o Option[T]) UnwrapUnchecked() T
UnwrapUnchecked returns the contained value.
func (Option[T]) XAnd ¶ added in v0.7.0
XAnd returns [`None`] if the option is [`None`], otherwise returns `optb`.
func (Option[T]) XAndThen ¶ added in v0.7.0
XAndThen returns [`None`] if the option is [`None`], otherwise calls `f` with the
func (Option[T]) XMap ¶ added in v0.7.0
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
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
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
XOkOr transforms the `Option[T]` into a [`Result[any]`], mapping [`Some(v)`] to [`Ok(v)`] and [`None`] to [`Err(err)`].
type Ordering ¶ added in v1.1.2
type Ordering struct {
// contains filtered or unexported fields
}
Ordering represents the result of a comparison between two values.
func Greater ¶ added in v1.1.2
func Greater() Ordering
Greater returns an Ordering representing "greater than".
type PureInteger ¶ added in v1.1.2
type PureInteger interface {
int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64
}
PureInteger represents pure integer types without type aliases.
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
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
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
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
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 ¶
Err wraps a failure result. NOTE: Even if err is nil, Err(nil) still represents an error state. This follows declarative programming principles: calling Err() explicitly declares an error result, regardless of the error value. This is consistent with Rust's Result::Err(()) semantics.
Example:
```go
result := gust.Err[string](nil) // This is an error state, even though err is nil
if result.IsErr() {
fmt.Println("This will be printed")
}
```
func (Result[T]) And2 ¶ added in v1.8.0
And2 returns `r` if `r` is `Err`, otherwise returns `Ret(v2, err2)`.
func (Result[T]) AndThen ¶
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]) AndThen2 ¶ added in v1.8.0
AndThen2 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]) AsPtr ¶ added in v1.5.2
func (r Result[T]) AsPtr() *T
AsPtr returns its pointer or nil.
func (*Result[T]) Catch ¶ added in v1.5.3
func (r *Result[T]) Catch()
Catch catches any panic and converts it to a Result error. It catches:
- *ErrBox (gust's own error type)
- error (regular Go errors, wrapped in ErrBox)
- any other type (wrapped in ErrBox)
Example:
```go
func example() (result Result[string]) {
defer result.Catch()
Err[int]("int error").UnwrapOrThrow()
return Ok[string]("ok")
}
```
func (Result[T]) ContainsErr ¶
ContainsErr returns true if the result is an error containing the given value.
func (Result[T]) Expect ¶
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 ¶
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]) Flatten ¶ added in v1.8.0
Flatten converts from `(gust.Result[T], error)` to gust.Result[T].
Examples ¶
var r1 = gust.Ok(1)
var err1 = nil
var result1 = r1.Flatten(err1)
assert.Equal(t, gust.Ok[int](1), result1)
var r2 = gust.Ok(1)
var err2 = errors.New("error")
var result2 = r2.Flatten(err2)
assert.Equal(t, "error", result2.Err().Error())
var r3 = gust.Err(errors.New("error")) var err3 = nil var result3 = r3.Flatten(err3) assert.Equal(t, "error", result3.Err().Error())
func (Result[T]) Inspect ¶
Inspect calls the provided closure with a reference to the contained value (if no error).
func (Result[T]) InspectErr ¶
InspectErr calls the provided closure with a reference to the contained error (if error).
func (Result[T]) IsErr ¶
IsErr returns true if the result is error. NOTE: This is determined by whether t.IsSome() is false, not by e.IsEmpty(). This ensures that Err(nil) is correctly identified as an error state, following declarative programming principles where Err() explicitly declares an error result.
func (Result[T]) IsErrAnd ¶
IsErrAnd returns true if the result is error and the value inside it matches a predicate.
func (Result[T]) IsOk ¶
IsOk returns true if the result is Ok. NOTE: This is determined by whether t.IsSome() is true, not by e.IsEmpty(). This ensures that Err(nil) is correctly identified as an error state, following declarative programming principles where Err() explicitly declares an error result.
func (Result[T]) IsOkAnd ¶
IsOkAnd returns true if the result is Ok and the value inside it matches a predicate.
func (Result[T]) Map ¶
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 ¶
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 ¶
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
MarshalJSON implements the json.Marshaler interface.
func (*Result[T]) NextBack ¶ added in v0.7.0
NextBack returns the next element from the back of the iterator.
func (Result[T]) Or ¶
Or returns `r2` if `r` is `Err`, otherwise returns `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]) Or2 ¶ added in v1.8.0
Or2 returns `Ret(v2, err2)` if `r` is `Err`, otherwise returns `r`.
func (Result[T]) OrElse ¶
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]) OrElse2 ¶ added in v1.8.0
OrElse2 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
Remaining returns the number of remaining elements in the iterator.
func (*Result[T]) UnmarshalJSON ¶ added in v0.6.0
UnmarshalJSON implements the json.Unmarshaler interface.
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. NOTE: This panics *ErrBox (not error) to be consistent with Result.UnwrapOrThrow() and allow Result.Catch() to properly handle it.
func (Result[T]) UnwrapErr ¶
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 ¶
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 (*ErrBox). NOTE:
If there is an error, that panic should be caught with `Result.Catch()`
func (Result[T]) UnwrapUnchecked ¶
func (r Result[T]) UnwrapUnchecked() T
UnwrapUnchecked returns the contained T.
func (Result[T]) XAnd ¶ added in v0.7.0
XAnd returns res if the result is Ok, otherwise returns the error of self.
func (Result[T]) XAnd2 ¶ added in v1.8.0
XAnd2 returns `r` if `r` is `Err`, otherwise returns `Ret(v2, err2)`.
func (Result[T]) XAndThen ¶ added in v0.7.0
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]) XAndThen2 ¶ added in v1.8.0
XAndThen2 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
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
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
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.
type SizeIterable ¶ added in v0.7.0
SizeIterable represents an iterable that knows its remaining size.
type SyncMap ¶ added in v1.4.0
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]) LoadAndDelete ¶ added in v1.4.0
LoadAndDelete deletes the value for a key, returning the previous value if any.
func (*SyncMap[K, V]) LoadOrStore ¶ added in v1.4.0
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
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.
type Void ¶ added in v0.7.0
type Void = *struct{}
Void is a type that represents the absence of a value.
type VoidResult ¶ added in v1.11.0
VoidResult is an alias for Result[Void], representing a result that only indicates success or failure. This is equivalent to Rust's Result<(), E> and provides a simpler API than Result[Void].
Example:
```go
var result gust.VoidResult = gust.RetVoid(err)
if result.IsErr() {
fmt.Println(result.Err())
}
```
Source Files
¶
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 provides a complete implementation of Rust's Iterator trait in Go.
|
Package iter provides a complete implementation of Rust's Iterator trait in Go. |
|
Package ret provides helper functions for working with gust.Result types.
|
Package ret provides helper functions for working with gust.Result types. |
|
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. |
