Skip to content

Commit eebb9db

Browse files
committed
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 <[email protected]>
1 parent 451cf3e commit eebb9db

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

doc/go_spec.html

+14
Original file line numberDiff line numberDiff line change
@@ -2513,10 +2513,24 @@ <h3 id="Composite_literals">Composite literals</h3>
25132513
generates a pointer to a unique <a href="#Variables">variable</a> initialized
25142514
with the literal's value.
25152515
</p>
2516+
25162517
<pre>
25172518
var pointer *Point3D = &amp;Point3D{y: 1000}
25182519
</pre>
25192520

2521+
<p>
2522+
Note that the <a href="#The_zero_value">zero value</a> for a slice or map
2523+
type is not the same as an initialized but empty value of the same type.
2524+
Consequently, taking the address of an empty slice or map composite literal
2525+
does not have the same effect as allocating a new slice or map value with
2526+
<a href="#Allocation">new</a>.
2527+
</p>
2528+
2529+
<pre>
2530+
p1 := &[]int{} // p1 points to an initialized, empty slice with value []int{} and length 0
2531+
p2 := new([]int) // p2 points to an uninitialized slice with value nil and length 0
2532+
</pre>
2533+
25202534
<p>
25212535
The length of an array literal is the length specified in the literal type.
25222536
If fewer elements than the length are provided in the literal, the missing

0 commit comments

Comments
 (0)