Arrays and Slices

Array

An array has a fixed size.

Since arrays has static size, its memory is allocated only once.

If ellipsis "..." is used in-place of size, the length of the array is inferred from the number of values declared.  

Syntax

var array_name [capacity]type

var array_name = [capacity]datatype{values}

var array_name = [...]datatype{values}

Example

var characters := [...]string{"Sheldon", "Leonard", "Wolowitz", "Rajesh"}

primes := [5]{2, 3, 5, 7, 11}

Slices

A slice is dynamically sized.

A slice does not store any data. It describes the portion of the underlying array.

Changing the elements of the slice modifies the underlying array and other slices that share the same underlying array will also have the changes.

A slice literal is similar to an array literal without the length. Internally, it creates the array and builds a slice on top of it.

For an array [10]int, the slice equivalents are array[0:10], array[:10], array[0:], array[:]

The length of the slice is the number of elements it contains and the capacity of the slice is the number of elements the underlying array has, starting from the fist element in slice. 

You can also associate a capacity of your own to a slice with [low: high: max] syntax. Here, value of max  must be less than or equal to the capacity of the source slice and the capacity of the new slice becomes max-low

Syntax

slice_name := []type{values}

slice_name := array_name[start:end]

slice_name := array[low: high: max]

Example

s := []int{2, 3, 5, 7, 11, 13}

// Slice the slice to give it zero length.

s = s[:0]    // Length - 0, Capacity - 6, []

// Extend its length.

s = s[:4]    // Length - 4, Capacity - 6, [2, 3, 5, 7] 

// Drop its first two values.

s = s[2:]    // Length - 2, Capacity - 4, [5, 7]

// Extend its length

s = s[0:3]    // Length - 3, Capacity - 4, [5, 7, 11]

You are not allowed to access indexes in the original data past that slice length.

Accessing an element not in the slice, even if it is within the capacity will cause error.

s = s[3]       // Accessing value 13panic: runtime error: index out of range [3] with length 3

slice := []int{2, 3, 5, 7, 11, 13}

slice := slice[1:3:5]    // Length - 2, Capacity - 4, [3, 5]

slice := slice[:3:6]     // Attempt to extend capacity beyond source capacitypanic: runtime error: slice bounds out of range [::6] with capacity 4

slice := slice[:3:2]    // Attempt to reduce the capacity below the lengthinvalid slice indices: 2 < 3

// Multi dimensional slices - tic-tac-toe board

board := [][]string{

    []string{"_", "_", "_"},

    []string{"_", "_", "_"},

    []string{"_", "_", "_"},

}

Comments