navidrome/utils/gg/gg.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

49 lines
1.3 KiB
Go
Raw Normal View History

2023-02-15 20:18:53 -05:00
// Package gg implements simple "extensions" to Go language. Based on https://github.com/icza/gog
package gg
2023-03-26 21:26:55 -04:00
// If returns v if it is a non-zero value, orElse otherwise.
2023-02-15 20:18:53 -05:00
//
// This is similar to elvis operator (?:) in Groovy and other languages.
// Note: Different from the real elvis operator, the orElse expression will always get evaluated.
2023-03-26 21:26:55 -04:00
func If[T comparable](v T, orElse T) T {
2023-02-15 20:18:53 -05:00
var zero T
if v != zero {
return v
}
return orElse
}
2023-03-26 21:26:55 -04:00
2023-05-22 11:59:33 -04:00
// P returns a pointer to a value, or nil if the value is the zero value of the type.
func P[T comparable](t T) *T {
2023-03-26 21:26:55 -04:00
var zero T
2023-05-22 11:59:33 -04:00
if t == zero {
return nil
}
return &t
}
// V returns the value of a pointer, or the zero value of the type if the pointer is nil.
func V[T comparable](p *T) T {
var zero T
if p == nil {
return zero
}
return *p
}
2023-03-26 21:26:55 -04:00
2023-05-22 11:59:33 -04:00
// 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")
func Coalesce[T comparable](values ...T) (v T) {
var zero T
for _, v = range values {
2023-03-26 21:26:55 -04:00
if v != zero {
2023-05-22 11:59:33 -04:00
return
2023-03-26 21:26:55 -04:00
}
}
2023-05-22 11:59:33 -04:00
return
2023-03-26 21:26:55 -04:00
}