new

package module
v0.21.1-0...-d92da1f Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2021 License: MIT Imports: 0 Imported by: 0

README

new.Of

A helper function to create a pointer to a new variable of a particular value in Go 1.18+.

strptr1 := new.Of("meaning of life")
strptr2 := new.Of("meaning of life")
strptr1 != strptr2 // true
*strptr1 == *strptr2 // true

intp1 := new.Of(42)
intp2 := new.Of(42)
intp1 != intp2 // true
*intp1 == *intp2 // true

type MyFloat float64
fp := new.Of[MyFloat](42)
fp != nil // true
*fp == 42 // true

Installation

As of November 2021, Go 1.18 is not released, but you can install Go tip with

$ go install golang.org/dl/gotip@latest
$ gotip download
$ gotip init me/myproject
$ gotip get github.com/carlmjohnson/new

FAQs

Oh god

I mean, honestly, this isn't even my worst idea for generics yet.

What problem does this solve exactly?

In Go, you cannot return a pointer to an expression, although you can return a pointer to a struct literal. As a result, return &struct{ 42 } is legal, but return &42 is not. To work around this, many popular packages include pointer helpers, such as aws.String and github.Int64. Thanks to generics, now one function can solve this problem once and for all.

How can you name a package new?

new is a built-in function, not a keyword, so it is legal to shadow the name. If this is a problem for your code because you are still using the built-in new function in legacy code, you can use an import alias for this package.

What does test coverage look like?

100%, baby.

Should I use this package?

Ideally, newof will become a built-in function in a future version of Go. Until then, this is fine.

fine

Documentation

Overview

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

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Of

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

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

Example
package main

import (
	"fmt"

	"github.com/carlmjohnson/new"
)

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

	intp1 := new.Of(42)
	intp2 := new.Of(42)
	fmt.Println(intp1 != intp2)
	fmt.Println(*intp1 == *intp2)

	type MyFloat float64
	fp := new.Of[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