/pointer

Work fearlessly with pointers in Go

Primary LanguageGoMIT LicenseMIT

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.