Skip to content
/ ptr Public

Ever need "&42" in Go? You are in the right place

License

Notifications You must be signed in to change notification settings

mrkagelui/ptr

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ptr.Of anything!

Check out my value package to do value.Of()!

GitHub go.mod Go version GitHub Workflow Status codecov Go Report Card GitHub made-with-Go goptr

Why this utility?

In many occasions, we need to take the address of a constant, e.g., an interface requires a nil-able integer, without this, we need to do

func thatFunc(i *int) {
	// does something useful
}

func main() {
	myImportantNum := 5
	thatFunc(&myImportantNum)
}

This utility helps you do

func thatFunc(i *int) {
	// does something useful
}

func main() {
	thatFunc(ptr.Of(5))
}

Why doesn't Go allow me to do &5?

Because 5 is a constant. As this answer points out, if you could take the address of a constant, you could change the value of that constant and jeopardize the entire world!

However, often we just want a pointer whose pointed value is given. This library provides a syntactic sugar by assigning that constant to a variable and returning the address of that variable. Thanks to generics introduced in Go 1.18, this is greatly simplified!

Warning: since this works by assigning constants to variables, there is a risk of losing precision or even compilation failure, for example, the following will fail to build.

package main

import "github.com/mrkagelui/ptr"

func main() {
	print(ptr.Of(2e308)) // will fail to build
}

Because 2e308 exceeds the maximum value of float64 type, which is inferred by the compiler, but is still a legit constant, which is unlimited. For more information about constants in Go, refer to the official blog.

How to use

By the spirit of "a little copying is better than a little dependency", I encourage you to simply copy the Of function in your project. However, if you don't mind having this dependency:

As this implementation relies on generics, you need to be using Go >1.18.

  1. With Go installed, run
go get -u github.com/mrkagelui/ptr
  1. Import this:
import "github.com/mrkagelui/ptr"
  1. Start using it!
package main

import "github.com/mrkagelui/ptr"

func main() {
	print(ptr.Of(5))
}

About

Ever need "&42" in Go? You are in the right place

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages