5

GitHub - carlmjohnson/new: A helper function to create a pointer to a new object...

 2 years ago
source link: https://github.com/carlmjohnson/new
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK