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>
This commit is contained in:
Alan Donovan 2025-09-17 22:24:57 -04:00 committed by Gopher Robot
parent 74cc463f9e
commit eb78f13c9f
2 changed files with 51 additions and 6 deletions

View file

@ -7806,12 +7806,32 @@ min(x, y, z) == min(min(x, y), z)
<h3 id="Allocation">Allocation</h3>
<p>
The built-in function <code>new</code> takes a type <code>T</code>,
allocates storage for a <a href="#Variables">variable</a> of that type
at run time, and returns a value of type <code>*T</code>
<a href="#Pointer_types">pointing</a> to it.
The variable is initialized as described in the section on
<a href="#The_zero_value">initial values</a>.
The built-in function <code>new</code> creates a new, initialized
<a href="#Variables">variable</a> and returns
a <a href="#Pointer_types">pointer</a> to it.
It accepts a single argument, which may be either an expression or a type.
</p>
<p>
If the argument <code>expr</code> is an expression of
type <code>T</code>, or an untyped constant expression
whose <a href="#Constants">default type</a> is <code>T</code>,
then <code>new(expr)</code> allocates a variable of
type <code>T</code>, initializes it to the value
of <code>expr</code>, and returns its address, a value of
type <code>*T</code>.
</p>
<p>
If the argument is a type <code>T</code>, then <code>new(T)</code>
allocates a variable initialized to
the <a href="#The_zero_value">zero value</a> of type <code>T</code>.
</p>
<p>
For example, <code>new(123)</code> and <code>new(int)</code> each
return a pointer to a new variable of type <code>int</code>.
The value of the first variable is <code>123</code>, and the value
of the second is <code>0</code>.
</p>
<pre class="grammar">

View file

@ -1,3 +1,28 @@
## Changes to the language {#language}
<!-- https://go.dev/issue/45624 --->
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),
})
}
```