Array

caution

Arrays are value types.

Slices are reference types.

The type [n]T is an array of n values of type T.

The expression

var a [10]int

declares a variable a as an array of ten integers.

An array's length is part of its type, so arrays cannot be resized. This seems limiting, but don't worry; Go provides a convenient way of working with arrays.

package main
import "fmt"
func main() {
var a [2]string
a[0] = "Hello"
a[1] = "World"
fmt.Println(a[0], a[1])
fmt.Println(a)
primes := [6]int{2, 3, 5, 7, 11, 13}
fmt.Println(primes)
}

Slices

An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array. In practice, slices are much more common than arrays.

The type []T is a slice with elements of type T.

A slice is formed by specifying two indices, a low and high bound, separated by a colon:

a[low : high]

This selects a half-open range which includes the first element, but excludes the last one.

The following expression creates a slice which includes elements 1 through 3 of a:

a[1:4]
package main
import "fmt"
func main() {
primes := [6]int{2, 3, 5, 7, 11, 13}
var s []int = primes[1:4]
fmt.Println(s)
}
// [3 5 7]
hint

Slices are like references to arrays.

A slice does not store any data, it just describes a section of an underlying array.

Changing the elements of a slice modifies the corresponding elements of its underlying array.

Other slices that share the same underlying array will see those changes.

package main
import "fmt"
func main() {
names := [4]string{
"John",
"Paul",
"George",
"Ringo",
}
fmt.Println(names)
a := names[0:2]
b := names[1:3]
fmt.Println(a, b)
b[0] = "XXX"
fmt.Println(a, b)
fmt.Println(names)
}
/*
[John Paul George Ringo]
[John Paul] [Paul George]
[John XXX] [XXX George]
[John XXX George Ringo]
*/

Slice literals

A slice literal is like an array literal without the length.

This is an array literal:

[3]bool{true, true, false}

And this creates the same array as above, then builds a slice that references it:

[]bool{true, true, false}
package main
import "fmt"
func main() {
q := []int{2, 3, 5, 7, 11, 13}
fmt.Println(q)
r := []bool{true, false, true, true, false, true}
fmt.Println(r)
s := []struct {
i int
b bool
}{
{2, true},
{3, false},
{5, true},
{7, true},
{11, false},
{13, true},
}
fmt.Println(s)
}
/*
[2 3 5 7 11 13]
[true false true true false true]
[{2 true} {3 false} {5 true} {7 true} {11 false} {13 true}]
*/

Slice defaults

When slicing, you may omit the high or low bounds to use their defaults instead.

The default is zero for the low bound and the length of the slice for the high bound.

For the array

var a [10]int

these slice expressions are equivalent:

a[0:10]
a[:10]
a[0:]
a[:]
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
s = s[1:4]
fmt.Println(s)
s = s[:2]
fmt.Println(s)
s = s[1:]
fmt.Println(s)
}
//
[3 5 7]
[3 5]
[5]

Slice length and capacity

A slice has both a length and a capacity.

The length of a slice is the number of elements it contains.

caution

The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.

The length and capacity of a slice s can be obtained using the expressions len(s) and cap(s).

You can extend a slice's length by re-slicing it, provided it has sufficient capacity.

package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
// Slice the slice to give it zero length.
s = s[:0]
printSlice(s)
// Extend its length.
s = s[:4]
printSlice(s)
// Drop its first two values.
s = s[2:]
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
/*
len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]
*/

Nil slices

The zero value of a slice is nil.

A nil slice has a length and capacity of 0 and has no underlying array.

package main
import "fmt"
func main() {
var s []int
fmt.Println(s, len(s), cap(s))
if s == nil {
fmt.Println("nil!")
}
}
// Excepted results:
[] 0 0
nil!

Creating a slice with make

Slices can be created with the built-in make function; this is how you create dynamically-sized arrays.

The make function allocates a zeroed array and returns a slice that refers to that array:

a := make([]int, 5) // len(a)=5

To specify a capacity, pass a third argument to make:

b := make([]int, 0, 5) // len(b)=0, cap(b)=5
b = b[:cap(b)] // len(b)=5, cap(b)=5
b = b[1:] // len(b)=4, cap(b)=4
package main
import "fmt"
func main() {
a := make([]int, 5)
printSlice("a", a)
b := make([]int, 0, 5)
printSlice("b", b)
c := b[:2]
printSlice("c", c)
d := c[2:5]
printSlice("d", d)
}
func printSlice(s string, x []int) {
fmt.Printf("%s len=%d cap=%d %v\n",
s, len(x), cap(x), x)
}
/*
a len=5 cap=5 [0 0 0 0 0]
b len=0 cap=5 []
c len=2 cap=5 [0 0]
d len=3 cap=3 [0 0 0]
*/

Slices of slices

Slices can contain any type, including other slices.

package main
import (
"fmt"
"strings"
)
func main() {
// Create a tic-tac-toe board.
board := [][]string{
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
}
// The players take turns.
board[0][0] = "X"
board[2][2] = "O"
board[1][2] = "X"
board[1][0] = "O"
board[0][2] = "X"
for i := 0; i < len(board); i++ {
fmt.Printf("%s\n", strings.Join(board[i], " "))
}
}
/*
X _ X
O _ X
_ _ O
*/

Appending to a slice

Go provides a built-in append function. The documentation of the built-in package describes append.

func append(s []T, vs ...T) []T

The first parameter s of append is a slice of type T, and the rest are T values to append to the slice.

The resulting value of append is a slice containing all the elements of the original slice plus the provided values.

{% hint style="warning" %} If the backing array of s is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array. {% endhint %}

(To learn more about slices, read the Slices: usage and internals article.)

package main
import "fmt"
func main() {
var s []int
printSlice(s)
// append works on nil slices.
s = append(s, 0) //
// the capacity now is 2 instead of 1
// because a new array has been created and the size is doubled
printSlice(s)
// The slice grows as needed.
s = append(s, 1)
printSlice(s)
// We can add more than one element at a time.
s = append(s, 2, 3, 4)
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
/*
len=0 cap=0 []
len=1 cap=2 [0]
len=2 cap=2 [0 1]
len=5 cap=8 [0 1 2 3 4]
*/

Range

The range form of the for loop iterates over a slice or map.

When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.

{% hint style="danger" %} The second is a copy of the element at that index, so

  1. Use index to update the element.
  2. Or use pointers to update the element {% endhint %}
package main
import "fmt"
var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}
func main() {
for i, v := range pow {
fmt.Printf("2**%d = %d\n", i, v)
}
}
/*
2**0 = 1
2**1 = 2
2**2 = 4
2**3 = 8
2**4 = 16
2**5 = 32
2**6 = 64
2**7 = 128
*/

You can skip the index or value by assigning to _.

for i, _ := range pow
for _, value := range pow

If you only want the index, you can omit the second variable.

for i := range pow
package main
import "fmt"
func main() {
pow := make([]int, 10)
for i := range pow {
pow[i] = 1 << uint(i) // == 2**i
}
for _, value := range pow {
fmt.Printf("%d\n", value)
}
}
/*
1
2
4
8
16
32
64
128
256
512
*/

Playground

Initialization

package main
import (
"fmt"
)
func main() {
ints1 := [3]int{1,2,3} // this is an array
fmt.Printf("%v\n", ints1)
ints2 := [...]int{1,2,3} // this is an array
fmt.Printf("%v\n", ints2)
ints3 := []int{1,2,3} // this is a slice
fmt.Printf("%v\n", ints3)
var ints4 [3]int
fmt.Printf("%v\n", ints4)
}
// Expected results:
[1 2 3]
[1 2 3]
[1 2 3]
[0 0 0]
package main
import (
"fmt"
)
func main() {
var matrix [2][2]int = [2][2]int{[2]int{1,0}, [2]int{0,1}}
fmt.Println(matrix)
}
// [[1 0] [0 1]]

Copy

package main
import (
"fmt"
)
func main() {
a := [3]int{1,2,3}
fmt.Printf("%v\n", a)
b := a
b[0] = 0
fmt.Printf("%v\n", a)
fmt.Printf("%v\n", b)
c := &a
c[0] = 0
fmt.Printf("%v\n", a)
fmt.Printf("%v\n", c)
}
//
[1 2 3]
[1 2 3]
[0 2 3]
[0 2 3]
&[0 2 3]

Append

package main
import (
"fmt"
)
func main() {
a := []int{1,2,3}
fmt.Printf("%v\n", a)
a = append(a, 4)
fmt.Printf("%v\n", a)
a = append(a, 5, 6)
fmt.Printf("%v\n", a)
a = append(a, []int{7, 9}...) // ... is spread out operator
fmt.Printf("%v\n", a)
}
//
[1 2 3]
[1 2 3 4]
[1 2 3 4 5 6]
[1 2 3 4 5 6 7 9]

Caution

package main
import (
"fmt"
)
func main() {
a := []int{1, 2, 3333, 4, 5}
fmt.Printf("%v\n", a)
b := append(a[:2], a[3:]...)
fmt.Printf("%v\n", b)
fmt.Printf("%v\n", a)
}
//
[1 2 3333 4 5]
[1 2 4 5]
[1 2 4 5 5]
Last updated on