value.Of anything!

Check out my ptr package to do ptr.Of()!

GitHub go.mod Go version GitHub Workflow Status codecov Go Report Card GitHub made-with-Go gopher_unboxed

Why this utility?

Because I bet you are wary 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!

How to use

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.

  1. With Go installed, run
go get -u github.com/mrkagelui/value
  1. Import this:
import "github.com/mrkagelui/value"
  1. Start using it!

package main

import "github.com/mrkagelui/value"

func main() {
	var ptr *int
	print(value.Of(ptr))
}

GitHub

View Github