elgopher / ptr

Generic Go functions to get optional values

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

About

Generic Go functions to get optional values

License:MIT License


Languages

Language:Go 100.0%