Go Slices: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 57: Line 57:


* Specification https://golang.org/ref/spec#Appending_and_copying_slices
* Specification https://golang.org/ref/spec#Appending_and_copying_slices
<tt>append()</tt> adds element at the end of the slice, increasing its length. The addition is operated by writing the values in the underlying array, unless the array is not long enough. In this case, a new array long enough to accommodate the new elements is created and the original array values are copied across.
The function always creates a new slice instance.


==<tt>copy()</tt>==
==<tt>copy()</tt>==


* Specification https://golang.org/ref/spec#Appending_and_copying_slices
* Specification https://golang.org/ref/spec#Appending_and_copying_slices

Revision as of 00:29, 28 March 2016

Internal

Overview

A slice is a reference type that implements a dynamic array. Slices are indexable, and they have a variable length. They are always associated with an underlying array, and the slice length cannot be longer than the underlying array - but it can be shorter. The slice's capacity is equal to the length on the underlying array.

TODO Deep difference between slice and array (memory model, etc.)

Declaration

A slice declaration is similar to an array's except the length is not specified. The slice is created with a zero length.

var s []int

Type inferred declaration, where the length and the capacity of the slice are specified can be performed using make().

The slices can also be created with the "slice" expression:

<array_identifier>[<low>:<high>]

Example:

var a [5]int
s := a[0:2]

The "low" index is the index where to start the slice and "high" is the index where to end the slice - but not index itself.

Special forms of the "slice" expression:

  • a[i:] is equivalent with a[i:len(a)].
  • a[:i] is equivalent with a[0:i]
  • a[:] is equivalent with a[0:len(a)]

Slice Operators and Functions

make()

<slice_identifier> := make([]<slice_element_type>, <slice_length>, <capacity>)
s := make([]int, 5)
s1 := make([]int, 5, 10)

append()

append() adds element at the end of the slice, increasing its length. The addition is operated by writing the values in the underlying array, unless the array is not long enough. In this case, a new array long enough to accommodate the new elements is created and the original array values are copied across.

The function always creates a new slice instance.

copy()