Check out my value package to do value.Of()!
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))
}
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.
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.
- With Go installed, run
go get -u github.com/mrkagelui/ptr
- Import this:
import "github.com/mrkagelui/ptr"
- Start using it!
package main
import "github.com/mrkagelui/ptr"
func main() {
print(ptr.Of(5))
}