Check out my ptr package to do ptr.Of()!
Because I bet you are weary of
var v T
if ptr != nil {
v = *ptr
}
or
var v T
if ptr1 != nil {
return *ptr1
}
if ptr2 != nil {
return *ptr2
}
return v
With this utility, you can
v := value.Of(ptr)
return value.OfFirstNotNil(ptr1, ptr2)
If you need a non-zero default value, there are OfOrDefault
and OfFirstNotNilOrDefault
variants as well!
If you want to receive an error if all pointers are nil, there is OfFirstNotNilOrError
variant available.
By the spirit of "a little copying is better than a little dependency", I encourage you to simply copy the
Of
/OfFirstNotNil
functions in your project. However, if you don't mind having this dependency:
As this implementation relies on generics, you need to be using Go >=1.18.
- With Go installed, run
go get -u github.com/mrkagelui/value
- Import this:
import "github.com/mrkagelui/value"
- Start using it!
package main
import "github.com/mrkagelui/value"
func main() {
var ptr *int
print(value.Of(ptr))
}
Because it would look like
if v, err := value.OfOrError(p); err != nil {
// handle error
}
which is hardly shorter than
if p == nil {
// handle nil pointer
}