From eb78f13c9f195ba11fd9518257b6e45997b14de5 Mon Sep 17 00:00:00 2001 From: Alan Donovan Date: Wed, 17 Sep 2025 22:24:57 -0400 Subject: [PATCH] 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 LUCI-TryBot-Result: Go LUCI Reviewed-by: Robert Findley --- doc/go_spec.html | 32 ++++++++++++++++++++++++++------ doc/next/2-language.md | 25 +++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 6 deletions(-) diff --git a/doc/go_spec.html b/doc/go_spec.html index 183bc7fb37..b67eaf9999 100644 --- a/doc/go_spec.html +++ b/doc/go_spec.html @@ -7806,12 +7806,32 @@ min(x, y, z) == min(min(x, y), z)

Allocation

-The built-in function new takes a type T, -allocates storage for a variable of that type -at run time, and returns a value of type *T -pointing to it. -The variable is initialized as described in the section on -initial values. + The built-in function new creates a new, initialized + variable and returns + a pointer to it. + + It accepts a single argument, which may be either an expression or a type. +

+

+ If the argument expr is an expression of + type T, or an untyped constant expression + whose default type is T, + then new(expr) allocates a variable of + type T, initializes it to the value + of expr, and returns its address, a value of + type *T. +

+

+ If the argument is a type T, then new(T) + allocates a variable initialized to + the zero value of type T. +

+

+ For example, new(123) and new(int) each + return a pointer to a new variable of type int. + + The value of the first variable is 123, and the value + of the second is 0.

diff --git a/doc/next/2-language.md b/doc/next/2-language.md
index 61030bd676..ded7becf01 100644
--- a/doc/next/2-language.md
+++ b/doc/next/2-language.md
@@ -1,3 +1,28 @@
 ## Changes to the language {#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:
+
+```go
+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),
+	})
+}
+```
-- 
2.52.0