Skip to content

mrkagelui/value

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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 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.

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))
}

Frequently Asked Question

Why is there not OfOrError?

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
}