In Go 1.26, new() got a small upgrade that I've wanted for a long time.
You can now pass a value expression to new(), not just a type. The compiler infers the pointer type and initializes the memory with the result of that expression.
ptr := new(someExpression())This is a tiny change from a spec perspective, but it removes one of those little friction points that shows up all the time in real code.
The problem
Historically, Go hasn't allowed you to take the address of a literal or expression.
You've probably hit this when building structs that have optional pointer fields. It's especially common in tests.
Something like this:
Payload{
Price: 99.99,
Tax: &9.99, // not allowed
}Go simply won't let you do that.
The usual workaround
The most common solution is a small helper function:
func ptr[T any](v T) *T { return &v }Then you end up writing things like:
Tax: ptr(9.99)It works fine. I've used this pattern in a bunch of projects.
But it's still a workaround. You have to define the helper somewhere, people new to the codebase ask what it does, and every project seems to have its own version of it.
What it looks like now
With Go 1.26, you can just write:
func TestBuildPayload(t *testing.T) {
cases := []struct {
name string
expected Payload
}{
{"standard", Payload{Price: 99.99, Tax: new(9.99)}},
{"free", Payload{Price: 0.0, Tax: new(0.0)}},
{"reduced", Payload{Price: 145.0, Tax: new(14.50)}},
}
// ...
}The value sits right next to the field it belongs to. No helper functions, no extra noise.
And since new() is already a built-in, nobody has to wonder what's going on.
I've wanted this in Go for years, so it's nice to finally see it land.
