go/doc/next/2-language.md
Alan Donovan eb78f13c9f doc/go_spec.html: document new(expr)
Also, add a release note.

For #45624

Change-Id: I1a0e111e00885c9640c073000afb72731d0930fc
Reviewed-on: https://go-review.googlesource.com/c/go/+/704737
Auto-Submit: Alan Donovan <adonovan@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Robert Findley <rfindley@google.com>
2025-09-23 12:08:27 -07:00

755 B

Changes to the language

The built-in new function, which creates a new variable, now allows its operand to be an expression, specifying the initial value of the variable.

This feature is particularly useful when working with serialization packages such as encoding/json or protocol buffers that use a pointer to represent an optional value, as it enables an optional field to be populated in a simple expression, for example:

import "encoding/json"

type Person struct {
	Name string   `json:"name"`
	Age  *int     `json:"age"` // age if known; nil otherwise
}

func personJSON(name string, age int) ([]byte, error) {
	return json.Marshal(Person{
		Name: name,
		Age:  new(age),
	})
}