From 519725bb3c075ee2462c929f5997cb068e18466a Mon Sep 17 00:00:00 2001 From: Ondřej Surý Date: Mon, 26 Mar 2012 16:50:58 +0200 Subject: Imported Upstream version 2012.03.22 --- doc/articles/slices_usage_and_internals.html | 53 ++++------------------------ 1 file changed, 6 insertions(+), 47 deletions(-) (limited to 'doc/articles/slices_usage_and_internals.html') diff --git a/doc/articles/slices_usage_and_internals.html b/doc/articles/slices_usage_and_internals.html index c10dfe0ca..810b0a41f 100644 --- a/doc/articles/slices_usage_and_internals.html +++ b/doc/articles/slices_usage_and_internals.html @@ -1,11 +1,7 @@ - -

Go's slice type provides a convenient and efficient means of working with @@ -326,20 +322,7 @@ appends byte elements to a slice of bytes, growing the slice if necessary, and returns the updated slice value:

-
func AppendByte(slice []byte, data ...byte) []byte {
-    m := len(slice)
-    n := m + len(data)
-    if n > cap(slice) { // if necessary, reallocate
-        // allocate double what's needed, for future growth.
-        newSlice := make([]byte, (n+1)*2)
-        copy(newSlice, slice)
-        slice = newSlice
-    }
-    slice = slice[0:n]
-    copy(slice[m:n], data)
-    return slice
-}
+{{code "/doc/progs/slices.go" `/AppendByte/` `/STOP/`}}

One could use AppendByte like this: @@ -398,18 +381,7 @@ Since the zero value of a slice (nil) acts like a zero-length slice, you can declare a slice variable and then append to it in a loop:

-
// Filter returns a new slice holding only
-// the elements of s that satisfy f()
-func Filter(s []int, fn func(int) bool) []int {
-    var p []int // == nil
-    for _, i := range s {
-        if fn(i) {
-            p = append(p, i)
-        }
-    }
-    return p
-}
+{{code "/doc/progs/slices.go" `/Filter/` `/STOP/`}}

A possible "gotcha" @@ -428,13 +400,7 @@ searches it for the first group of consecutive numeric digits, returning them as a new slice.

-
var digitRegexp = regexp.MustCompile("[0-9]+")
-
-func FindDigits(filename string) []byte {
-    b, _ := ioutil.ReadFile(filename)
-    return digitRegexp.Find(b)
-}
+{{code "/doc/progs/slices.go" `/digit/` `/STOP/`}}

This code behaves as advertised, but the returned []byte points @@ -449,14 +415,7 @@ To fix this problem one can copy the interesting data to a new slice before returning it:

-
func CopyDigits(filename string) []byte {
-    b, _ := ioutil.ReadFile(filename)
-    b = digitRegexp.Find(b)
-    c := make([]byte, len(b))
-    copy(c, b)
-    return c
-}
+{{code "/doc/progs/slices.go" `/CopyDigits/` `/STOP/`}}

A more concise version of this function could be constructed by using -- cgit v1.2.3