Commit eebb9db0 authored by Robert Griesemer's avatar Robert Griesemer

spec: clarify the difference between &T{} and new(T)

Add a small paragraph and example pointing out
the difference for the case where T is a slice
or map. This is a common error for Go novices.

Fixes #29425.

Change-Id: Icdb59f25361e9f6a09b190fbfcc9ae0c7d90077b
Reviewed-on: https://go-review.googlesource.com/c/go/+/176338Reviewed-by: default avatarMatthew Dempsky <mdempsky@google.com>
parent 451cf3e2
...@@ -2513,10 +2513,24 @@ For array and slice literals the following rules apply: ...@@ -2513,10 +2513,24 @@ For array and slice literals the following rules apply:
generates a pointer to a unique <a href="#Variables">variable</a> initialized generates a pointer to a unique <a href="#Variables">variable</a> initialized
with the literal's value. with the literal's value.
</p> </p>
<pre> <pre>
var pointer *Point3D = &amp;Point3D{y: 1000} var pointer *Point3D = &amp;Point3D{y: 1000}
</pre> </pre>
<p>
Note that the <a href="#The_zero_value">zero value</a> for a slice or map
type is not the same as an initialized but empty value of the same type.
Consequently, taking the address of an empty slice or map composite literal
does not have the same effect as allocating a new slice or map value with
<a href="#Allocation">new</a>.
</p>
<pre>
p1 := &[]int{} // p1 points to an initialized, empty slice with value []int{} and length 0
p2 := new([]int) // p2 points to an uninitialized slice with value nil and length 0
</pre>
<p> <p>
The length of an array literal is the length specified in the literal type. The length of an array literal is the length specified in the literal type.
If fewer elements than the length are provided in the literal, the missing If fewer elements than the length are provided in the literal, the missing
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment