Skip to content

elgopher/ptr

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ptr

Generic functions to get optional values

Go Reference codecov Project Status: Active – The project has reached a stable, usable state and is being actively developed.

Problems with Go optional values

By convention, optional values in Go are pointers:

type Input struct {
	RequiredField string
	OptionalField *string
}

But such structs cannot be initialized in a single expression:

in := Input{
	RequiredField: "works",
	OptionalField: &("does not work"),
}

And accessing optional fields makes code look ugly:

if in.OptionalField != nil && *in.OptionalField == "value" {
    ...    	
}

Sometimes even unsafe:

value := "v1"
in.OptionalField = &value
value = "v2" // ups... in.OptionalField is changed too! 

This tiny packages simplifies the use of optional values

One-line initialization:

import "github.com/elgopher/ptr"

in := Input{
	RequiredField: "works",
	OptionalField: ptr.To("this also works"),
}

Getting values without boilerplate code:

if ptr.Value(in.OptionalField) == "value" {
	// if in.OptionalField is nil then zero value is returned ("" for string)
    ...    	
}

or get value by specifying the default value when in.OptionalField is nil:

v := ptr.ValueOrDefault(in.OptionalField, "defaultValue")

Safe code:

value := "v1"
in.OptionalField = ptr.To(value)
value = "v2" // in.OptionalField is not changed

or

newPointer := ptr.Copy(in.OptionalField)

Installation

go get github.com/elgopher/ptr@latest