Arrays

Arrays

An array in Go is a fixed-length data type that contains a contiguous block of elements of the same type. This could be a built-in type such as integers and strings, or it can be a struct type.

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

  • An array's length is part of its type, so arrays cannot be resized.

  • Arrays are efficient data structures because the memory is laid out in sequence.

  • Arrays are values. Assigning one array to another copies all the elements. In particular, if you pass an array to a function, it will receive a copy of the array, not a pointer to it.

var a [10]int // a as an array of ten integers.

var b = [6]int{2, 3, 5, 7, 11, 13} // array literal

// length of array determined from literal
var c = [...]int{1, 1, 2, 3, 5, 8}

// Initialize only the 2th element
var d = [5]string{2: "magic"}

// sparse array
var x = [12]int{1, 5: 4, 6, 10: 100, 15}

// Typed unsigned int could be used as array length
const size uint = 3
var a2 [2 * size]bool

Copying an array

Copying an array of pointers copies the pointer values and not the values that the pointers are pointing to.

var s = "23";
var a [3]*string // [<nil> <nil> <nil>]
a2 := [3]*string{&s, &s, &s}

a = a2
// a = [0x1040c128 0x1040c128 0x1040c128]
// a2 = [0x1040c128 0x1040c128 0x1040c128]

Compare arrays

Если тип элементов массива является сравниваемым, то таким же и является тип массива, так что мы можем сравнить два массива такого типа непосредственно при помощи оператора ==.

Array as function argument

Passing an array between functions can be an expensive operation in terms of memory and performance. When you pass variables between functions, they’re always passed by value. When your variable is an array, this means the entire array, regardless of its size, is copied and passed to the function. You can pass a pointer to the array.

// Allocate an array of 8 megabytes.
var array [1e6]int

// Pass the address of the array to the function foo.
foo(&array)

// Function foo accepts a pointer to an array of one million integers.
func foo(array *[1e6]int) {
    ...
}

Last updated