aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRob Pike <r@golang.org>2013-09-27 22:12:31 +1000
committerRob Pike <r@golang.org>2013-09-27 22:12:31 +1000
commitd4c23261dc940eb2cb841a1a84832174e6bac0c4 (patch)
tree7102c663f9029272b84279835e743090e205d6b3
parent357626c292524e07a7994137d63324f2e193becf (diff)
go.blog/slices: fix bug in Append
The code didn't work but the blog runs the previous simple version, which does, so when you hit Run it looks like it's working. It only had two bugs (so far). Thanks to shelah.kell@gmail.com for noticing. R=adg CC=golang-dev https://golang.org/cl/14036043
-rw-r--r--content/slices.article2
-rw-r--r--content/slices/prog140.go6
2 files changed, 4 insertions, 4 deletions
diff --git a/content/slices.article b/content/slices.article
index eb974e8..de76408 100644
--- a/content/slices.article
+++ b/content/slices.article
@@ -443,7 +443,7 @@ allocated memory, and then to copy the appending items to the end of the old dat
Try it; the behavior is the same as before:
-.play -edit slices/prog130.go /START/,/END/
+.play -edit slices/prog140.go /START/,/END/
* Append: The built-in function
diff --git a/content/slices/prog140.go b/content/slices/prog140.go
index 306d6f2..ab04d97 100644
--- a/content/slices/prog140.go
+++ b/content/slices/prog140.go
@@ -11,7 +11,8 @@ import (
// Append appends the elements to the slice.
// Efficient version.
func Append(slice []int, elements ...int) []int {
- total := len(slice) + len(items)
+ n := len(slice)
+ total := len(slice) + len(elements)
if total > cap(slice) {
// Reallocate. Grow to 1.5 times the new size, so we can still grow.
newSize := total*3/2 + 1
@@ -19,9 +20,8 @@ func Append(slice []int, elements ...int) []int {
copy(newSlice, slice)
slice = newSlice
}
- n := len(slice)
slice = slice[:total]
- copy(slice[:n], elements)
+ copy(slice[n:], elements)
return slice
}