summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorSam Zaydel <szaydel@gmail.com>2014-08-10 20:02:31 -0700
committerSam Zaydel <szaydel@gmail.com>2014-08-10 20:02:31 -0700
commit19bd3cdd0b938ece7de01f685b5c99e927b53b1e (patch)
tree210175924974d328bbcff3356a7f084f862feef6
parenta9daab714af9c1db9a48311d050d7f8d340b8048 (diff)
In golang slices are dynamic, so a mention of append() for slice updates seems to be appropriate.
-rw-r--r--go.html.markdown14
1 files changed, 14 insertions, 0 deletions
diff --git a/go.html.markdown b/go.html.markdown
index 656b1051..ba65d1e5 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -101,6 +101,20 @@ can include line breaks.` // Same string type.
var d2 [][]float64 // Declaration only, nothing allocated here.
bs := []byte("a slice") // Type conversion syntax.
+ // Because they are dynamic, slices can be appended to on-demand.
+ // To append elements to a slice, built-in append() function is used.
+ // First argument is a slice to which we are appending. Commonly,
+ // the array variable is updated in place, as in example below.
+ s := []int{1, 2, 3} // Result is a slice of length 3.
+ s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6.
+ fmt.Println(s) // Updated slice is now [1 2 3 4 5 6]
+ // To append another slice, instead of list of atomic elements we can
+ // pass a reference to a slice or a slice literal like this, with a
+ // trailing elipsis, meaning take an array and unpack its elements,
+ // appending them to the slice.
+ s = append(s, []int{7, 8, 9}...) // Second argument is an array literal.
+ fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9]
+
p, q := learnMemory() // Declares p, q to be type pointer to int.
fmt.Println(*p, *q) // * follows a pointer. This prints two ints.