Go Devs: You Can Delete This Code Now

The Only Bamboo
246 followers
9 Video Views·Mar 20, 2026
🚀 Write Go Like a Senior Engineer → https://levelupgo.dev
Before Go (Golang) 1.26, you couldn't take the address of a literal value. Want to set a pointer field inline? You either created a temp variable or wrote a ptr() helper. Every Go project has one.
Go 1.26 extends the built-in new() function to accept expressions.
0:00 Before Go 1.26: Challenges with Passing Values as Pointers
1:51 Go 1.26: Introducing the `new` Function for Direct Pointer Creation
Before Go 1.26 there was no way to pass a value directly as a pointer. You always had to store
it in a variable first or create a helper function. That's no longer the case. Here's
what's changed. Here we have a order struct. When you want the field to be optional you would make
it into a pointer. Here we are trying to initialize the order struct and if we would run this we would
and the reason is in Go you cannot take an address of a value like this. Before Go 1.26 how you would
solve this is the first way you would create a temporary variable. We could say discount and
then we can set that to be 0.15 and here we would just pass our discount variable and if we now try
to run this so it works but this is quite ugly. We are creating a temporary variable that we will
throw away just to silence the compiler. Now imagine then if you had like 10 optional fields
that could get pretty messy fast and another way how to solve this is that you would create the
utils function and here we have a generic function. It takes a value and it gives back a pointer to
that value so here we could just remove that variable and inside discount we would say ptr
and then just pass 0.15. Now we can try to run it again and we can see it works as expected
and this pattern is so common so you would find it in a lot of different code bases. For example
here we have the AWS SDK and we can see a lot of these functions. They take a value and they return
a pointer. All these functions do the same thing but they are just for different types. With Go 1.26
we can now delete this function and all we have to do now is here we can say new instead. Let's now
try to run it and we can see it compiles without any problems. So before new only used to take a
type and it will return a zero value but now you can also pass it a expression. If you ever
implemented one of those pointer functions you can finally delete it.
