tools

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2023 License: MIT Imports: 1 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Annotate

func Annotate(err error, ctx string) error

Annotate adds extra context to an error message, essentially via a call to fmt.Errorf("%s: %w", ctx, err), but if the error was nil, no wrapped error is prodduced and nil is returned, allowing for clean returns from functions.

func Annotatef

func Annotatef(err error, format string, args ...any) error

Annotatef is like annotate, but accepting Printf style arguments to generate the context message. Like with Annotate, no work is done if the error was nil, and a nil is simply returned.

func Check

func Check(err error)

Check accepts an error and will panic with it if it's non-nil.

func CleanErrors

func CleanErrors[T any](value T, err error) (T, error)

CleanErrors wraps the return values from a function of the form (value,error) and ensures only one of the value or error is returned. If the error is non-nil, then a zero value is returned for value. This makes it easier to have "clean" return values where it doesn't make sense for the user to proceed when there is an error.

func Compose

func Compose[X, Y, Z any](f func(X) Y, g func(Y) Z) func(X) Z

Compose builds a composite function from the to input functions f, and g. The returned function computes g(f(x)).

func Must

func Must[T any](value T, err error) T

Must accepts a value/error pair, and returns the value as long as the error is nil. If there is a non-nil error Must will panic with it.

func Or

func Or[T comparable](items ...T) T

Or returns the first item from its list of arguments that isn't a zero value and returns zero if none are found.

Note: this is likely to be added to the stdlib as cmp.Or in go 1.22.

func Pick

func Pick[T any](condition bool, trueValue, falseValue T) T

Pick returns trueValue if condition is true, falseValue otherwise. This allows for simple selection of a value based on a condition that would normally result in a 4 line (or more) code block due to the lack of a ternary operator in Go.

Unlike the ?: operator in C, since this is still a function, any computation needed to create the values passed as trueValue and falseValue are likely still performed as it's not guaranteed to be a short-circuit. Inlining may still produce benefits, but any side effects of producing the values will always happen, regardless of which value is selected by the condition.

Types

This section is empty.

Jump to

Keyboard shortcuts

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