pointer

package module
v0.1.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

License Go Reference Go Report Card GitHub CI codecov

Work fearlessly with pointers in Go

Project Description

package pointer is a tiny, simple and obvious library helping you to always work safely with pointers and avoid the dreaded nil pointer dereference 🚀

Installation

To use this project in your code:

go get github.com/FollowTheProcess/pointer@latest

And then simply:

import "github.com/FollowTheProcess/pointer"

Quickstart

Using pointer is so easy, you already know how to do it!

import (
    "fmt"

    "github.com/FollowTheProcess/pointer"
)

func main() {
    var s *string // nil

    // More code here, you've forgotten `s` is nil by now!
    // but pointer has you covered!
    str := pointer.Or(s, "hello")

    fmt.Println(str) // "hello"

    // We just want the zero value if it's nil
    fmt.Println(pointer.OrDefault(s)) // ""
}

pointer.Or will return the pointer it's passed in only if it's not nil! Otherwise you'll get back the value you provided.

If you just want the zero value instead, use pointer.OrDefault

Credits

This package was created with copier and the FollowTheProcess/go_copier project template.

Documentation

Overview

Package pointer is a tiny, simple and obvious library to help deal safely with pointers

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Or

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

Or returns the value p is pointing to if it is not nil, else v.

var s *string // nil pointer
str := pointer.Or(s, "default")
fmt.Println(str) // "default"
Example
package main

import (
	"fmt"

	"github.com/FollowTheProcess/pointer"
)

func main() {
	var s1 *string // nil pointer
	s2 := "hello"

	fmt.Printf("%q\n", pointer.Or(s1, "default"))
	fmt.Printf("%q\n", pointer.Or(&s2, "you won't see me"))

}
Output:
"default"
"hello"

func OrDefault

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

OrDefault returns the value p is pointing to if it is not nil, otherwise the zero value for the type T.

var s *string // nil pointer
str := pointer.OrDefault(s)
fmt.Println(str) // ""
Example
package main

import (
	"fmt"

	"github.com/FollowTheProcess/pointer"
)

func main() {
	var s1 *string // nil pointer
	s2 := "wow!"

	fmt.Printf("%q\n", pointer.OrDefault(s1))
	fmt.Printf("%q\n", pointer.OrDefault(&s2))

}
Output:
""
"wow!"

Types

This section is empty.

Jump to

Keyboard shortcuts

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