aboutsummaryrefslogtreecommitdiff
path: root/doc/go_spec.html
diff options
context:
space:
mode:
authorRobert Griesemer <gri@golang.org>2019-05-09 17:35:29 -0700
committerRobert Griesemer <gri@golang.org>2019-05-13 21:24:51 +0000
commiteebb9db0ef1a4cad2f5dd7e8b90f699a1d50bf91 (patch)
tree12b3f805e55daa9223c69e8bcfbf0832d1e4f9ed /doc/go_spec.html
parent451cf3e2cd8950571f436896a3987343f8c2d7f6 (diff)
downloadgo-eebb9db0ef1a4cad2f5dd7e8b90f699a1d50bf91.tar.gz
go-eebb9db0ef1a4cad2f5dd7e8b90f699a1d50bf91.zip
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/+/176338 Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Diffstat (limited to 'doc/go_spec.html')
-rw-r--r--doc/go_spec.html14
1 files changed, 14 insertions, 0 deletions
diff --git a/doc/go_spec.html b/doc/go_spec.html
index 158146b9c0..dea3afe498 100644
--- a/doc/go_spec.html
+++ b/doc/go_spec.html
@@ -2513,11 +2513,25 @@ For array and slice literals the following rules apply:
generates a pointer to a unique <a href="#Variables">variable</a> initialized
with the literal's value.
</p>
+
<pre>
var pointer *Point3D = &amp;Point3D{y: 1000}
</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>
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
elements are set to the zero value for the array element type.