aboutsummaryrefslogtreecommitdiff
path: root/content/slices/prog110.go
diff options
context:
space:
mode:
Diffstat (limited to 'content/slices/prog110.go')
-rw-r--r--content/slices/prog110.go35
1 files changed, 35 insertions, 0 deletions
diff --git a/content/slices/prog110.go b/content/slices/prog110.go
new file mode 100644
index 0000000..5bee1c4
--- /dev/null
+++ b/content/slices/prog110.go
@@ -0,0 +1,35 @@
+// 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"
+)
+
+// Extend extends the slice by adding the element to the end.
+func Extend(slice []int, element int) []int {
+ n := len(slice)
+ if n == cap(slice) {
+ // Slice is full; must grow.
+ // We double its size and add 1, so if the size is zero we still grow.
+ newSlice := make([]int, len(slice), 2*len(slice)+1)
+ copy(newSlice, slice)
+ slice = newSlice
+ }
+ slice = slice[0 : n+1]
+ slice[n] = element
+ return slice
+}
+
+func main() {
+ // START OMIT
+ slice := make([]int, 0, 5)
+ for i := 0; i < 10; i++ {
+ slice = Extend(slice, i)
+ fmt.Printf("len=%d cap=%d slice=%v\n", len(slice), cap(slice), slice)
+ fmt.Println("address of 0th element:", &slice[0])
+ }
+ // END OMIT
+}