Interesting development in the world of Go: in 1.26, the new() function will now accept expressions, not just types. This returns a pointer to the value, which will be useful for those types that use pointers for their fields:
type User struct {
Age *int
}
user := User{}
var age int = 10
user.Age = new(age)
It also works for literal values, so that temporary age
variable is strictly not necessary, although the linked post does state that it requires some consideration for types. Having user.Age = new(10)
will work without issue as new
will return a *int
; but if Age
were a *uint
, you’ll get a type error.
I go on about unnecessary pointer types in the past (and will probably continue to do so in the future). To me, it’s just one of those paper-cuts you encounter in your day to day that you know can be made easier. So I consider this a welcome change. It’s not going to same me a ton on code, but every little bit helps.