pointer

package module
v0.23.0 Latest Latest
Warning

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

Go to latest
Published: May 12, 2023 License: MIT Imports: 0 Imported by: 0

README

pointer Go Reference

Some generic Go pointer helpers:

// Start with a null pointer
var strptr *string

// pointer.Deref safely dereferences a nil pointer into its empty value
fmt.Println(pointer.Deref(strptr) == "") // prints true

// pointer.Coalesce lets us specify a default value for a nil pointer
fmt.Println(pointer.Coalesce(strptr, "hello, world")) // prints "hello, world"

// We can create a pointer to a string or other primitive type with pointer.New
newptr := pointer.New("meaning of life") // takes a pointer to a string, wow!

// pointer.First returns the first pointer that isn't nil.
strptr = pointer.First(strptr, newptr) // returns newptr

Documentation

Overview

Package pointer contains generic pointer helper functions

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Coalesce

func Coalesce[T any](p *T, v T) T

Coalesce returns *p if p is not nil, otherwise v.

Example
package main

import (
	"fmt"

	"github.com/carlmjohnson/pointer"
)

func main() {
	var np *int
	fmt.Println(pointer.Coalesce(np, 1))
	np = new(int)
	fmt.Println(pointer.Coalesce(np, 1))
}
Output:

1
0

func Deref

func Deref[T any](p *T) T

Deref returns *p if p is not nil, otherwise the zero value of T.

Example
package main

import (
	"fmt"

	"github.com/carlmjohnson/pointer"
)

func main() {
	var np *int
	fmt.Println(pointer.Deref(np))
	one := 1
	np = &one
	fmt.Println(pointer.Deref(np))
}
Output:

0
1

func First

func First[T any](ptrs ...*T) *T

First returns the first non-nil pointer it is passed.

Example
package main

import (
	"fmt"

	"github.com/carlmjohnson/pointer"
)

func main() {
	type config struct{ string }
	userInput := func() *config {
		return nil
	}
	someConfig := pointer.First(
		userInput(),
		&config{"default config"},
	)
	fmt.Println(someConfig)
}
Output:

&{default config}

func New

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

New allocates a new variable of a given value and returns a pointer to it.

Example
package main

import (
	"fmt"

	"github.com/carlmjohnson/pointer"
)

func main() {
	strptr1 := pointer.New("meaning of life")
	strptr2 := pointer.New("meaning of life")
	fmt.Println(strptr1 != strptr2)
	fmt.Println(*strptr1 == *strptr2)

	intp1 := pointer.New(42)
	intp2 := pointer.New(42)
	fmt.Println(intp1 != intp2)
	fmt.Println(*intp1 == *intp2)

	type MyFloat float64
	fp := pointer.New[MyFloat](42)
	fmt.Println(fp != nil)
	fmt.Println(*fp == 42)

}
Output:

true
true
true
true
true
true

Types

This section is empty.

Jump to

Keyboard shortcuts

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