funcs

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2024 License: Apache-2.0 Imports: 1 Imported by: 0

Documentation

Overview

Package funcs provides some common generic functions.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Compare

func Compare[T cmp.Ordered](left, right T) int

Compare compares left and right and returns

 0 if left == right
-1 if left <  right
+1 if left >  right

func Must added in v0.3.0

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

Must returns value if err is nil. Or, panic with err.

func Unwrap

func Unwrap[T any](v interface{}) (inner T, ok bool)

Unwrap unwraps the inner value of v with ok==true if v has implemented the interface { Unwrap() T } or { Get() T }. Or, assert v to T and return it with ok==false instead.

Example
/*
	type (
		getter  string
		wrapper string
	)

	func (g getter) Get() string     { return string(g) }
	func (w wrapper) Unwrap() string { return string(w) }
*/) }
*/

s, ok := Unwrap[string](getter("a"))
fmt.Println(s, ok)

s, ok = Unwrap[string](wrapper("b"))
fmt.Println(s, ok)

s, ok = Unwrap[string]("c")
fmt.Println(s, ok)

func() {
	defer func() { fmt.Println("panic:", recover()) }()
	Unwrap[string](123)
}()
Output:

a true
b true
c false
panic: interface conversion: interface {} is int, not string

func UnwrapAll

func UnwrapAll[T any](v interface{}) T

UnwrapAll is the same as Unwrap, but unwraps the innest value of v.

Example
err1 := fmt.Errorf("err1")
err2 := fmt.Errorf("err2: %w", err1)
err3 := fmt.Errorf("err3: %w", err2)
err4 := fmt.Errorf("err4: %w", err3)

err := UnwrapAll[error](err4)
fmt.Println(err)
Output:

err1

Types

This section is empty.

Jump to

Keyboard shortcuts

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