Documentation
¶
Overview ¶
Package g contains general, generic extensions to the Go language, requiring generics (introduced in Go 1.18).
Index ¶
- func Coalesce[T comparable](values ...T) (v T)
- func Deref[T any](p *T, def ...T) (result T)
- func First[T any](first T, _ ...any) T
- func If[T any](cond bool, vtrue, vfalse T) T
- func Must[T any](v T, err error) T
- func Ptr[T any](v T) *T
- func Second[T any](_ any, second T, _ ...any) T
- func Third[T any](_, _ any, third T, _ ...any) T
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Coalesce ¶
func Coalesce[T comparable](values ...T) (v T)
Coalesce returns the first non-zero value from listed arguments. Returns the zero value of the type parameter if no arguments are given or all are the zero value. Useful when you want to initialize a variable to the first non-zero value from a list of fallback values.
For example:
hostVal := Coalesce(hostName, os.Getenv("HOST"), "localhost")
Note: the same functionality has been added to Go 1.22 in cmp.Or()
func Deref ¶
func Deref[T any](p *T, def ...T) (result T)
Deref "safely" dereferences a pointer, returns the pointed value. If the pointer is nil, the (first) def is returned. If def is not specified, the zero value of T is returned.
func First ¶
First returns the first argument. Useful when you want to use the first result of a function call that has more than one return values (e.g. in a composite literal or in a condition).
For example:
func f() (i, j, k int, s string, f float64) { return }
p := image.Point{
X: First(f()),
}
func If ¶
If returns vtrue if cond is true, vfalse otherwise.
Useful to avoid an if statement when initializing variables, for example:
min := If(i > 0, i, 0)
func Must ¶
Must takes 2 arguments, the second being an error. If err is not nil, Must panics. Else the first argument is returned.
Useful when inputs to some function are provided in the source code, and you are sure they are valid (if not, it's OK to panic). For example:
t := Must(time.Parse("2006-01-02", "2022-04-20"))
func Ptr ¶
func Ptr[T any](v T) *T
Ptr returns a pointer to the passed value.
Useful when you have a value and need a pointer, e.g.:
func f() string { return "foo" }
foo := struct{
Bar *string
}{
Bar: Ptr(f()),
}
func Second ¶
Second returns the second argument. Useful when you want to use the second result of a function call that has more than one return values (e.g. in a composite literal or in a condition).
For example:
func f() (i, j, k int, s string, f float64) { return }
p := image.Point{
X: Second(f()),
}
Types ¶
This section is empty.