Go Slices: usage and internals — The Go Blog
The Go Blog
Go Slices: usage and internals
Andrew Gerrand
5 January 2011
Introduction
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.
Arrays
The slice type is an abstraction built on top of Go’s array type, and so to understand slices we must first understand arrays.
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.
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:
The in-memory representation of [4]int is just four integer values laid out sequentially:
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.
An array literal can be specified like so:
Or, you can have the compiler count the array elements for you:
In both cases, the type of b is [2]string .
Slices
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.
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.
A slice literal is declared just like an array literal, except you leave out the element count:
A slice can be created with the built-in function called make , which has the signature,
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.
When the capacity argument is omitted, it defaults to the specified length. Here’s a more succinct version of the same code:
The length and capacity of a slice can be inspected using the built-in len and cap functions.
The next two sections discuss the relationship between length and capacity.
The zero value of a slice is nil . The len and cap functions will both return 0 for a nil slice.
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).
The start and end indices of a slice expression are optional; they default to zero and the slice’s length respectively:
This is also the syntax to create a slice given an array:
Slice internals
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).
Our variable s , created earlier by make([]byte, 5) , is structured like this:
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.
As we slice s , observe the changes in the slice data structure and their relation to the underlying array:
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:
Earlier we sliced s to a length shorter than its capacity. We can grow s to its capacity by slicing it again:
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.
Growing slices (the copy and append functions)
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 :
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.
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.
Using copy , we can simplify the code snippet above:
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:
One could use AppendByte like this:
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.
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
The append function appends the elements x to the end of the slice s , and grows the slice if a greater capacity is needed.
To append one slice to another, use . to expand the second argument to a list of arguments.
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:
A possible «gotcha»
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.
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.
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.
To fix this problem one can copy the interesting data to a new slice before returning it:
A more concise version of this function could be constructed by using append . This is left as an exercise for the reader.
Урок №138. Перегрузка оператора индексации []
Обновл. 2 Янв 2020 |
В этом уроке мы рассмотрим перегрузку оператора индексации, его использование и нюансы, связанные с ним.
Перегрузка оператора индексации []
При работе с массивами оператор индексации ([]) используется для выбора определённых элементов:
Рассмотрим следующий класс IntArray, в котором в качестве переменной-члена используется массив:
Поскольку переменная-член m_array является закрытой, то мы не имеем прямого доступа к m_array через объект array . Это означает, что мы не можем напрямую получить или установить значения элементов m_array . Что делать?
Хотя это работает, но это не очень удобно. Рассмотрим следующий пример:
Присваиваем ли мы элементу 4 значение 5 или элементу 5 значение 4? Без просмотра определения метода setItem() этого не понять.
Можно также просто возвращать весь массив ( m_array ) и использовать оператор [] для доступа к его элементам:
Но можно сделать ещё проще, перегрузив оператор индексации.
Оператор индексации является одним из операторов, перегрузка которого должна выполняться через метод класса. Функция перегрузки оператора [] всегда будет принимать один параметр: значение индекса (элемент массива, к которому требуется доступ). В нашем случае с IntArray нам нужно, чтобы пользователь просто указал в квадратных скобках индекс для возврата значения элемента по этому индексу:
Теперь, всякий раз, когда мы будем использовать оператор индексации ([]) с объектом класса IntArray, компилятор будет возвращать соответствующий элемент массива m_array ! Это позволит нам непосредственно как получать, так и присваивать значения элементам m_array :
Всё просто. При обработке array[4] компилятор сначала проверяет, есть ли функция перегрузки оператора []. Если есть, то он передаёт в функцию перегрузки значение внутри квадратных скобок (в данном случае 4 ) в качестве аргумента.
Обратите внимание, хотя мы можем указать параметр по умолчанию для функции перегрузки оператора [], но, в данном случае, если мы, используя [], не укажем внутри скобок значение индекса, то получим ошибку.
Почему оператор индексации [] использует возврат по ссылке?
Рассмотрим подробнее, как обрабатывается стейтмент array[4] = 5 . Поскольку приоритет оператора индексации выше приоритета оператора присваивания, то сначала выполняется часть array[4] . array[4] приводит к вызову функции перегрузки оператора [], которая возвратит array.m_array[4] . Поскольку оператор [] использует возврат по ссылке, то он возвращает фактический элемент array.m_array[4] . Наше частично обработанное выражение становится array.m_array[4] = 5 , что является прямой операцией присваивания значения элементу массива.
Из урока №10 мы уже знаем, что любое значение, которое находится слева от оператора присваивания должно быть l-value (переменной с адресом в памяти). Поскольку результат выполнения оператора [] может использоваться в левой части операции присваивания (например, array[4] = 5 ), то возвращаемое значение оператора [] должно быть l-value. Ссылки же всегда являются l-values, так как их можно использовать только с переменными, которые имеют адреса памяти. Поэтому, используя возврат по ссылке, компилятор останется доволен, что возвращается l-value и никаких проблем не будет.
Рассмотрим, что произойдёт, если оператор [] будет использовать возврат по значению вместо возврата по ссылке. array[4] приведёт к вызову функции перегрузки оператора [], который будет возвращать значение элемента array.m_array[4] (не индекс, а значение по указанному индексу). Например, если значением m_array[4] является 7 , то выполнение оператора [] приведёт к возврату значения 7 . array[4] = 5 будет обрабатываться как 7 = 5 , что является бессмысленным! Если вы попытаетесь это сделать, то компилятор выдаст следующую ошибку:
C:VCProjectsTest.cpp(386) : error C2106: ‘=’ : left operand must be l-value
Использование оператора индексации с константными объектами класса
В примере выше метод operator[] не является константным, и мы можем использовать этот метод для изменения данных неконстантных объектов. Однако, что произойдёт, если наш объект класса IntArray будет const? В этом случае мы не сможем вызывать неконстантный operator[], так как он изменяет значения объекта (детальнее о классах и const читайте в уроке №123).
Хорошей новостью является то, что мы можем определить отдельно неконстантную и константную версии operator[]. Неконстантная версия будет использоваться с неконстантными объектами, а версия const с объектами const:
Arrays
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You have seen an example of arrays already, in the main method of the «Hello World!» application. This section discusses arrays in greater detail.
An array of 10 elements.
Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
The following program, ArrayDemo , creates an array of integers, puts some values in the array, and prints each value to standard output.
The output from this program is:
In a real-world programming situation, you would probably use one of the supported looping constructs to iterate through each element of the array, rather than write each line individually as in the preceding example. However, the example clearly illustrates the array syntax. You will learn about the various looping constructs ( for , while , and do-while ) in the Control Flow section.
Declaring a Variable to Refer to an Array
The preceding program declares an array (named anArray ) with the following line of code:
Like declarations for variables of other types, an array declaration has two components: the array’s type and the array’s name. An array’s type is written as type[] , where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty). An array’s name can be anything you want, provided that it follows the rules and conventions as previously discussed in the naming section. As with variables of other types, the declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type.
Similarly, you can declare arrays of other types:
You can also place the brackets after the array’s name:
However, convention discourages this form; the brackets identify the array type and should appear with the type designation.
Creating, Initializing, and Accessing an Array
One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for 10 integer elements and assigns the array to the anArray variable.
If this statement is missing, then the compiler prints an error like the following, and compilation fails:
The next few lines assign values to each element of the array:
Each array element is accessed by its numerical index:
Alternatively, you can use the shortcut syntax to create and initialize an array:
Here the length of the array is determined by the number of values provided between braces and separated by commas.
You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of brackets, such as String[][] names . Each element, therefore, must be accessed by a corresponding number of index values.
In the Java programming language, a multidimensional array is an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length, as shown in the following MultiDimArrayDemo program:
The output from this program is:
Finally, you can use the built-in length property to determine the size of any array. The following code prints the array’s size to standard output:
Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy data from one array into another:
The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.
The following program, ArrayCopyDemo , declares an array of char elements, spelling the word «decaffeinated.» It uses the System.arraycopy method to copy a subsequence of array components into a second array:
The output from this program is:
Array Manipulations
Arrays are a powerful and useful concept used in programming. Java SE provides methods to perform some of the most common manipulations related to arrays. For instance, the ArrayCopyDemo example uses the arraycopy method of the System class instead of manually iterating through the elements of the source array and placing each one into the destination array. This is performed behind the scenes, enabling the developer to use just one line of code to call the method.
For your convenience, Java SE provides several methods for performing array manipulations (common tasks, such as copying, sorting and searching arrays) in the java.util.Arrays class. For instance, the previous example can be modified to use the copyOfRange method of the java.util.Arrays class, as you can see in the ArrayCopyOfDemo example. The difference is that using the copyOfRange method does not require you to create the destination array before calling the method, because the destination array is returned by the method:
As you can see, the output from this program is the same ( caffein ), although it requires fewer lines of code. Note that the second parameter of the copyOfRange method is the initial index of the range to be copied, inclusively, while the third parameter is the final index of the range to be copied, exclusively. In this example, the range to be copied does not include the array element at index 9 (which contains the character a ).
Some other useful operations provided by methods in the java.util.Arrays class, are:
- Searching an array for a specific value to get the index at which it is placed (the binarySearch method).
- Comparing two arrays to determine if they are equal or not (the equals method).
- Filling an array to place a specific value at each index (the fill method).
- Sorting an array into ascending order. This can be done either sequentially, using the sort method, or concurrently, using the parallelSort method introduced in Java SE 8. Parallel sorting of large arrays on multiprocessor systems is faster than sequential array sorting.
The Go Blog
Go Slices: usage and internals
Andrew Gerrand
5 January 2011
Introduction
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.
Arrays
The slice type is an abstraction built on top of Go’s array type, and so to understand slices we must first understand arrays.
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.
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:
The in-memory representation of [4]int is just four integer values laid out sequentially:
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.
An array literal can be specified like so:
Or, you can have the compiler count the array elements for you:
In both cases, the type of b is [2]string .
Slices
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.
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.
A slice literal is declared just like an array literal, except you leave out the element count:
A slice can be created with the built-in function called make , which has the signature,
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.
When the capacity argument is omitted, it defaults to the specified length. Here’s a more succinct version of the same code:
The length and capacity of a slice can be inspected using the built-in len and cap functions.
The next two sections discuss the relationship between length and capacity.
The zero value of a slice is nil . The len and cap functions will both return 0 for a nil slice.
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).
The start and end indices of a slice expression are optional; they default to zero and the slice’s length respectively:
This is also the syntax to create a slice given an array:
Slice internals
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).
Our variable s , created earlier by make([]byte, 5) , is structured like this:
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.
As we slice s , observe the changes in the slice data structure and their relation to the underlying array:
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:
Earlier we sliced s to a length shorter than its capacity. We can grow s to its capacity by slicing it again:
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.
Growing slices (the copy and append functions)
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 :
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.
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.
Using copy , we can simplify the code snippet above:
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:
One could use AppendByte like this:
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.
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
The append function appends the elements x to the end of the slice s , and grows the slice if a greater capacity is needed.
To append one slice to another, use . to expand the second argument to a list of arguments.
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:
A possible «gotcha»
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.
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.
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.
To fix this problem one can copy the interesting data to a new slice before returning it:
A more concise version of this function could be constructed by using append . This is left as an exercise for the reader.