Arrays

suggest change

Arrays in Go have a fixed sized. They can’t grow.

Because of that arrays in Go are rarely used. Instead slices are used in most cases.

Zero value of array is an array where all values have zero value.

Elements of arrays are laid out in memory consecutively, which is good for speed.

Arrays are passed by value which means that passing an array argument to a function copies the whole array. This is slow if the array is large.

Array basics:

a := [2]int{4, 5} // array of 2 ints

// access element of array
fmt.Printf("a[1]: %d\n", a[1])

// set element of array
a[1] = 3

// get size of array
fmt.Printf("size of array  a: %d\n", len(a))

// when using [...] size will be deduced from { ... }
a2 := [...]int{4, 8, -1} // array of 3 integers
fmt.Printf("size of array a2: %d\n", len(a2))
a[1]: 5
size of array  a: 2
size of array a2: 3

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents