go/doc/next/2-language.md
Alan Donovan 77fc27972a doc/next: improve new(expr) release note
One reader pointed out that the example isn't compelling because
&age would have worked just as well. This CL changes the example
to use a nontrivial expression. Don't nitpick the arithmetic.

For #45624

Change-Id: Icc745f5ee7000c1d3559da1388c6a5596c4d1f46
Reviewed-on: https://go-review.googlesource.com/c/go/+/714040
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Alan Donovan <adonovan@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
2025-10-22 20:30:59 -07:00

32 lines
881 B
Markdown

## 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, born time.Time) ([]byte, error) {
return json.Marshal(Person{
Name: name,
Age: new(yearsSince(born)),
})
}
func yearsSince(t time.Time) int {
return int(time.Since(t).Hours() / (365.25 * 24)) // approximately
}
```