Start learning free

LESSON 88 OF 338 · ARRAYS I

Static Arrays in Go: Fixed-Size Arrays and Their Zero Values

Lesson Read the full explanation

When we're dealing with large amounts of data, we want to make sure we can organize and manage it properly.

In Go, we use arrays to store several pieces of data in one place. The items in an array must be of the same data type.

A static array or fixed array is an array for which the size / length is determined when the array is created and/or allocated.


Creation:

We create a static array by writing the var keyword, the array's name, the array's length inside [], and the data type of its elements:

var arrayOfStrings [5]string

In this program we created an array named arrayOfStrings that consists of 5 string items.

These 5 items are initialized with empty strings "" automatically.


Creation & Initialization:

There is a way to initialize an array at creation by using the := operator with an opening bracket, end it with a closing bracket, and put a comma between each entry, like this:

arrayOfStrings := [...]string{"AlgoCademy", "coding", "static arrays"}

We created an array named arrayOfStrings which consits of 3 string items: "AlgoCademy", "coding" and "static arrays".


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    GO · ARRAYS I

    Static Arrays in Go, explained

    What a static array is

    An array holds several values of the same type in one variable. In Go the number of elements is fixed when the array is created and can never change. This is why arrays of this kind are called static, or fixed-size. Use one when you know exactly how many items you need, such as 7 days of the week or the 3 colour channels of a pixel.

    The length is part of the array's type. [20]int and [10]int are two different types, in the same way that int and string are. The type of an array is written as the length in square brackets followed by the element type.

    Creating an array

    There are three common ways to create an array.

    Declaring with var

    var arrayOfStrings [5]string
    

    This creates an array of 5 strings. Go fills every element with the zero value of its type, which is "" for strings, 0 for integers and floats, and false for booleans. You never get uninitialised memory.

    An array literal

    fruits := [3]string{"mango", "kiwi", "grapefruit"}
    

    The type comes first, then the values in braces separated by commas. The short declaration := infers the variable's type from the literal. If you list fewer values than the length, the rest stay at their zero values; listing more is a compile error.

    Letting the compiler count

    arrayOfStrings := [...]string{"AlgoCademy", "coding", "static arrays"}
    

    With [...] in place of the number, the compiler counts the values. This array has length 3 and the type [3]string. The array is still fixed; ... only saves you from counting by hand.

    The lesson's exercise

    Step 1: an array of 20 integers

    The literal [20]int{} has an empty list of values, so every one of the 20 elements takes the zero value, 0. Storing it with := gives a variable named numbers.

    Step 2: an array of three strings

    The literal [3]string{"mango", "kiwi", "grapefruit"} gives the array its three values, stored as fruits.

    The solution in Go

    numbers := [20]int{}
    fruits := [3]string{"mango", "kiwi", "grapefruit"}
    

    Printing them with fmt.Println shows the contents in square brackets: numbers prints twenty zeros, and fruits prints [mango kiwi grapefruit]. The built-in len gives the length: len(numbers) is 20 and len(fruits) is 3.

    Using an array

    Elements are read and written by index, starting at 0:

    fruits[1] = "plum"
    fmt.Println(fruits[0], fruits)
    

    This prints mango [mango plum grapefruit]. The valid indices of fruits are 0, 1 and 2. A for i, f := range fruits loop visits each index and value in order.

    Go details that matter

    • The size is part of the type. Assigning a [10]int to a [20]int variable doesn't compile: cannot use other (variable of type [10]int) as [20]int value in assignment.
    • The size must be a constant. The length has to be known when the program is compiled. A variable such as n := 5 cannot be used as [n]int. When the size is only known while the program runs, use a slice.
    • Out-of-range indices. A constant index outside the array, such as numbers[25], is a compile error. A variable index that is out of range compiles, and then panics when the program runs with index out of range [20] with length 20.
    • Arrays are values. Assigning an array to another variable copies every element, and passing an array to a function passes a copy. Changing the copy does not change the original. If copyF := fruits and you then set copyF[0] = "pear", fruits[0] is still "mango". Arrays of the same type can also be compared with ==, which compares element by element.
    • Arrays are rarely passed around directly. Because of the copying and the fixed size, Go code more often uses slices, which are flexible views over arrays. Arrays are still the foundation that slices are built on.

    Common mistakes

    • Leaving out the length. []int{1, 2, 3} with empty brackets is a slice, not an array. The array needs either a number or ....
    • Using the wrong length. Writing [2]string{"mango", "kiwi", "grapefruit"} fails to compile, because there are more values than slots.
    • Counting from 1. The first element is at index 0 and the last is at len(array) - 1.
    • Expecting to grow. There is no way to add a 21st element to numbers. A different size means a different type.
    • Using := twice. A name can be declared once per scope; to change a value later, use = or an index assignment.

    Key takeaways

    • An array has a fixed length that is part of its type, written [N]T.
    • Elements start at their zero values and are accessed by index from 0.
    • Create arrays with var, with a literal like [3]string{...}, or with [...] to let the compiler count.
    • Arrays are copied when assigned or passed; slices are the flexible alternative.
    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free