pointer

package
v1.4.30-prerelease-v3 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2024 License: Apache-2.0 Imports: 0 Imported by: 2

README

pointer

Go Report Card Documentation license

TL;DR smplifies dealing with pointers in Go...

In Go, taking the address of a literal (string, number, etc) is illegal because it has ambiguous semantics. This fact (and dealing with that ambiguity) often makes Go code longer than it needs to be.

For example, assume you have a struct with all pointer fields... To populate it, you'd have to first define all the values outside of the struct definition:

myString := "string"
myBool := true
myInt := 999

s := MyStruct{
    MyString: &myString,
    MyBool:   &myBool,
    MyInt:    &myInt,
}

Using this library, this can be simplified to:

s := MyStruct{
    MyString: pointer.To("string"),
    MyBool:   pointer.To(true),
    MyInt:    pointer.To(999),
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func To

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

To returns the address of any given value. This is useful because in Go it is illegal to take the address of a literal value (i.e. is not possible to do &"string") - this helper function allows us to do pointer.To("string") in-line.

func ValueOrDefault

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

ValueOrDefault returns the value of dereferencing a pointer if the pointer is not nil, or a given default value if nil.

func ValueOrZero

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

ValueOrZero returns the value of dereferencing a pointer if the pointer is not nil, or the zero value of the type if nil.

Types

This section is empty.

Jump to

Keyboard shortcuts

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