Firmino Changani

Inline conversion of anything to a pointer - Golang

In Go, unless one is initialising a struct, one cannot outright create a pointer out of something without first initialising it to a variable:

 1package main
 2
 3type User struct {
 4    lastUpdatedAt *time.Time
 5}
 6
 7func main() {
 8    lastUpdatedAt := time.Now()
 9    user := User{
10        lastUpdatedAt: &lastUpdatedAt
11    }
12}

Even though the approach displayed above works just fine it still ends up requiring the initialisation of a variable that potentially won’t be used anywhere, and perhaps for the use-case above one would be better off by performing an inline conversion of the intended value to a pointer.

What I do and rather often, is to write a function that will receive anything and return that same thing as a pointer, here is how I express it in code:

1package main
2
3func ToPtr[T any](value T) *T {
4	return &value
5}

Here is the initial example rewritten with such a function:

 1package main
 2
 3type User struct {
 4    lastUpdatedAt *time.Time
 5}
 6
 7func main() {
 8    user := User{
 9        lastUpdatedAt: ToPtr(time.Now())
10    }
11}

And that’s all, thanks for passing by.

#golang

Reply to this post by email ↪