github.com/spotify/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/blog/content/go-slices-usage-and-internals.article (about)

     1  Go Slices: usage and internals
     2  5 Jan 2011
     3  Tags: slice, technical
     4  
     5  Andrew Gerrand
     6  
     7  * Introduction
     8  
     9  Go's slice type provides a convenient and efficient means of working with sequences of typed data. Slices are analogous to arrays in other languages, but have some unusual properties. This article will look at what slices are and how they are used.
    10  
    11  * Arrays
    12  
    13  The slice type is an abstraction built on top of Go's array type, and so to understand slices we must first understand arrays.
    14  
    15  An array type definition specifies a length and an element type. For example, the type `[4]int` represents an array of four integers. An array's size is fixed; its length is part of its type (`[4]int` and `[5]int` are distinct, incompatible types). Arrays can be indexed in the usual way, so the expression `s[n]` accesses the nth element, starting from zero.
    16  
    17  	var a [4]int
    18  	a[0] = 1
    19  	i := a[0]
    20  	// i == 1
    21  
    22  Arrays do not need to be initialized explicitly; the zero value of an array is a ready-to-use array whose elements are themselves zeroed:
    23  
    24  	// a[2] == 0, the zero value of the int type
    25  
    26  The in-memory representation of `[4]int` is just four integer values laid out sequentially:
    27  
    28  .image go-slices-usage-and-internals_slice-array.png
    29  
    30  Go's arrays are values. An array variable denotes the entire array; it is not a pointer to the first array element (as would be the case in C).  This means that when you assign or pass around an array value you will make a copy of its contents. (To avoid the copy you could pass a _pointer_ to the array, but then that's a pointer to an array, not an array.) One way to think about arrays is as a sort of struct but with indexed rather than named fields: a fixed-size composite value.
    31  
    32  An array literal can be specified like so:
    33  
    34  	b := [2]string{"Penn", "Teller"}
    35  
    36  Or, you can have the compiler count the array elements for you:
    37  
    38  	b := [...]string{"Penn", "Teller"}
    39  
    40  In both cases, the type of `b` is `[2]string`.
    41  
    42  * Slices
    43  
    44  Arrays have their place, but they're a bit inflexible, so you don't see them too often in Go code. Slices, though, are everywhere. They build on arrays to provide great power and convenience.
    45  
    46  The type specification for a slice is `[]T`, where `T` is the type of the elements of the slice. Unlike an array type, a slice type has no specified length.
    47  
    48  A slice literal is declared just like an array literal, except you leave out the element count:
    49  
    50  	letters := []string{"a", "b", "c", "d"}
    51  
    52  A slice can be created with the built-in function called `make`, which has the signature,
    53  
    54  	func make([]T, len, cap) []T
    55  
    56  where T stands for the element type of the slice to be created. The `make` function takes a type, a length, and an optional capacity. When called, `make` allocates an array and returns a slice that refers to that array.
    57  
    58  	var s []byte
    59  	s = make([]byte, 5, 5)
    60  	// s == []byte{0, 0, 0, 0, 0}
    61  
    62  When the capacity argument is omitted, it defaults to the specified length. Here's a more succinct version of the same code:
    63  
    64  	s := make([]byte, 5)
    65  
    66  The length and capacity of a slice can be inspected using the built-in `len` and `cap` functions.
    67  
    68  	len(s) == 5
    69  	cap(s) == 5
    70  
    71  The next two sections discuss the relationship between length and capacity.
    72  
    73  The zero value of a slice is `nil`. The `len` and `cap` functions will both return 0 for a nil slice.
    74  
    75  A slice can also be formed by "slicing" an existing slice or array. Slicing is done by specifying a half-open range with two indices separated by a colon. For example, the expression `b[1:4]` creates a slice including elements 1 through 3 of `b` (the indices of the resulting slice will be 0 through 2).
    76  
    77  	b := []byte{'g', 'o', 'l', 'a', 'n', 'g'}
    78  	// b[1:4] == []byte{'o', 'l', 'a'}, sharing the same storage as b
    79  
    80  The start and end indices of a slice expression are optional; they default to zero and the slice's length respectively:
    81  
    82  	// b[:2] == []byte{'g', 'o'}
    83  	// b[2:] == []byte{'l', 'a', 'n', 'g'}
    84  	// b[:] == b
    85  
    86  This is also the syntax to create a slice given an array:
    87  
    88  	x := [3]string{"Лайка", "Белка", "Стрелка"}
    89  	s := x[:] // a slice referencing the storage of x
    90  
    91  * Slice internals
    92  
    93  A slice is a descriptor of an array segment. It consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment).
    94  
    95  .image go-slices-usage-and-internals_slice-struct.png
    96  
    97  Our variable `s`, created earlier by `make([]byte,`5)`, is structured like this:
    98  
    99  .image go-slices-usage-and-internals_slice-1.png
   100  
   101  The length is the number of elements referred to by the slice. The capacity is the number of elements in the underlying array (beginning at the element referred to by the slice pointer). The distinction between length and capacity will be made clear as we walk through the next few examples.
   102  
   103  As we slice `s`, observe the changes in the slice data structure and their relation to the underlying array:
   104  
   105  	s = s[2:4]
   106  
   107  .image go-slices-usage-and-internals_slice-2.png
   108  
   109  Slicing does not copy the slice's data. It creates a new slice value that points to the original array. This makes slice operations as efficient as manipulating array indices. Therefore, modifying the _elements_ (not the slice itself) of a re-slice modifies the elements of the original slice:
   110  
   111  	d := []byte{'r', 'o', 'a', 'd'}
   112  	e := d[2:] 
   113  	// e == []byte{'a', 'd'}
   114  	e[1] = 'm'
   115  	// e == []byte{'a', 'm'}
   116  	// d == []byte{'r', 'o', 'a', 'm'}
   117  
   118  Earlier we sliced `s` to a length shorter than its capacity. We can grow s to its capacity by slicing it again:
   119  
   120  	s = s[:cap(s)]
   121  
   122  .image go-slices-usage-and-internals_slice-3.png
   123  
   124  A slice cannot be grown beyond its capacity. Attempting to do so will cause a runtime panic, just as when indexing outside the bounds of a slice or array. Similarly, slices cannot be re-sliced below zero to access earlier elements in the array.
   125  
   126  * Growing slices (the copy and append functions)
   127  
   128  To increase the capacity of a slice one must create a new, larger slice and copy the contents of the original slice into it. This technique is how dynamic array implementations from other languages work behind the scenes. The next example doubles the capacity of `s` by making a new slice, `t`, copying the contents of `s` into `t`, and then assigning the slice value `t` to `s`:
   129  
   130  	t := make([]byte, len(s), (cap(s)+1)*2) // +1 in case cap(s) == 0
   131  	for i := range s {
   132  	        t[i] = s[i]
   133  	}
   134  	s = t
   135  
   136  The looping piece of this common operation is made easier by the built-in copy function. As the name suggests, copy copies data from a source slice to a destination slice. It returns the number of elements copied.
   137  
   138  	func copy(dst, src []T) int
   139  
   140  The `copy` function supports copying between slices of different lengths (it will copy only up to the smaller number of elements). In addition, `copy` can handle source and destination slices that share the same underlying array, handling overlapping slices correctly.
   141  
   142  Using `copy`, we can simplify the code snippet above:
   143  
   144  	t := make([]byte, len(s), (cap(s)+1)*2)
   145  	copy(t, s)
   146  	s = t
   147  
   148  A common operation is to append data to the end of a slice. This function appends byte elements to a slice of bytes, growing the slice if necessary, and returns the updated slice value:
   149  
   150  	func AppendByte(slice []byte, data ...byte) []byte {
   151  	    m := len(slice)
   152  	    n := m + len(data)
   153  	    if n > cap(slice) { // if necessary, reallocate
   154  	        // allocate double what's needed, for future growth.
   155  	        newSlice := make([]byte, (n+1)*2)
   156  	        copy(newSlice, slice)
   157  	        slice = newSlice
   158  	    }
   159  	    slice = slice[0:n]
   160  	    copy(slice[m:n], data)
   161  	    return slice
   162  	}
   163  
   164  One could use `AppendByte` like this:
   165  
   166  	p := []byte{2, 3, 5}
   167  	p = AppendByte(p, 7, 11, 13)
   168  	// p == []byte{2, 3, 5, 7, 11, 13}
   169  
   170  Functions like `AppendByte` are useful because they offer complete control over the way the slice is grown. Depending on the characteristics of the program, it may be desirable to allocate in smaller or larger chunks, or to put a ceiling on the size of a reallocation.
   171  
   172  But most programs don't need complete control, so Go provides a built-in `append` function that's good for most purposes; it has the signature
   173  
   174  	func append(s []T, x ...T) []T 
   175  
   176  The `append` function appends the elements `x` to the end of the slice `s`, and grows the slice if a greater capacity is needed.
   177  
   178  	a := make([]int, 1)
   179  	// a == []int{0}
   180  	a = append(a, 1, 2, 3)
   181  	// a == []int{0, 1, 2, 3}
   182  
   183  To append one slice to another, use `...` to expand the second argument to a list of arguments.
   184  
   185  	a := []string{"John", "Paul"}
   186  	b := []string{"George", "Ringo", "Pete"}
   187  	a = append(a, b...) // equivalent to "append(a, b[0], b[1], b[2])"
   188  	// a == []string{"John", "Paul", "George", "Ringo", "Pete"}
   189  
   190  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:
   191  
   192  	// Filter returns a new slice holding only
   193  	// the elements of s that satisfy f()
   194  	func Filter(s []int, fn func(int) bool) []int {
   195  	    var p []int // == nil
   196  	    for _, v := range s {
   197  	        if fn(v) {
   198  	            p = append(p, v)
   199  	        }
   200  	    }
   201  	    return p
   202  	}
   203  
   204  * A possible "gotcha"
   205  
   206  As mentioned earlier, re-slicing a slice doesn't make a copy of the underlying array. The full array will be kept in memory until it is no longer referenced. Occasionally this can cause the program to hold all the data in memory when only a small piece of it is needed.
   207  
   208  For example, this `FindDigits` function loads a file into memory and searches it for the first group of consecutive numeric digits, returning them as a new slice.
   209  
   210  	var digitRegexp = regexp.MustCompile("[0-9]+")
   211  
   212  	func FindDigits(filename string) []byte {
   213  	    b, _ := ioutil.ReadFile(filename)
   214  	    return digitRegexp.Find(b)
   215  	}
   216  
   217  This code behaves as advertised, but the returned `[]byte` points into an array containing the entire file. Since the slice references the original array, as long as the slice is kept around the garbage collector can't release the array; the few useful bytes of the file keep the entire contents in memory.
   218  
   219  To fix this problem one can copy the interesting data to a new slice before returning it:
   220  
   221  	func CopyDigits(filename string) []byte {
   222  	    b, _ := ioutil.ReadFile(filename)
   223  	    b = digitRegexp.Find(b)
   224  	    c := make([]byte, len(b))
   225  	    copy(c, b)
   226  	    return c
   227  	}
   228  
   229  A more concise version of this function could be constructed by using `append`. This is left as an exercise for the reader.
   230  
   231  * Further Reading
   232  
   233  [[http://golang.org/doc/effective_go.html][Effective Go]] contains an in-depth treatment of [[http://golang.org/doc/effective_go.html#slices][slices]] and [[http://golang.org/doc/effective_go.html#arrays][arrays]], and the Go [[http://golang.org/doc/go_spec.html][language specification]] defines [[http://golang.org/doc/go_spec.html#Slice_types][slices]] and their [[http://golang.org/doc/go_spec.html#Length_and_capacity][associated]] [[http://golang.org/doc/go_spec.html#Making_slices_maps_and_channels][helper]] [[http://golang.org/doc/go_spec.html#Appending_and_copying_slices][functions]].