ptr

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 25, 2023 License: MIT Imports: 0 Imported by: 0

README

ptr

Generic functions to get optional values

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)
    ...    	
}
v := ptr.ValueOrDefault(in.OptionalField, "defaultValue")

Safe code:

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

Installation

go get github.com/elgopher/ptr@latest

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Copy

func Copy[T any](in *T) *T

Copy copies value behind the pointer and returns a new pointer to the copy.

func To

func To[T any](t T) *T

To returns a pointer to value. This function is very useful for single-line expressions, where "&" cannot be used:

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

func Value

func Value[T any](ptr *T) T

Value returns a value behind the pointer or zero value when value is nil.

func ValueOrDefault

func ValueOrDefault[T any](ptr *T, defaultValue T) T

ValueOrDefault returns a value behind the pointer or defaultValue when value is nil.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL