aboutsummaryrefslogtreecommitdiff
path: root/content/slices/prog140.go
diff options
context:
space:
mode:
Diffstat (limited to 'content/slices/prog140.go')
-rw-r--r--content/slices/prog140.go36
1 files changed, 36 insertions, 0 deletions
diff --git a/content/slices/prog140.go b/content/slices/prog140.go
new file mode 100644
index 0000000..306d6f2
--- /dev/null
+++ b/content/slices/prog140.go
@@ -0,0 +1,36 @@
+// Copyright 2013 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package main
+
+import (
+ "fmt"
+)
+
+// Append appends the elements to the slice.
+// Efficient version.
+func Append(slice []int, elements ...int) []int {
+ total := len(slice) + len(items)
+ if total > cap(slice) {
+ // Reallocate. Grow to 1.5 times the new size, so we can still grow.
+ newSize := total*3/2 + 1
+ newSlice := make([]int, total, newSize)
+ copy(newSlice, slice)
+ slice = newSlice
+ }
+ n := len(slice)
+ slice = slice[:total]
+ copy(slice[:n], elements)
+ return slice
+}
+
+func main() {
+ // START OMIT
+ slice1 := []int{0, 1, 2, 3, 4}
+ slice2 := []int{55, 66, 77}
+ fmt.Println(slice1)
+ slice1 = Append(slice1, slice2...) // The '...' is essential!
+ fmt.Println(slice1)
+ // END OMIT
+}