← Back to Go Course | Chapter 5: Arrays Slices Maps | Lesson 1 of 7

Arrays

An array is a fixed row of numbered lockers, each holding one item, where you decide exactly how many lockers exist before you start using them.

Declaring a Fixed-Size Array

An array type includes its length, like [5]int for an array of exactly five integers. Once declared, its size can never change -- this is fundamentally different from arrays/lists in dynamically sized languages.

Example: Declaring a Fixed-Size Array

markup
package main

import "fmt"

func main() {
	var scores [5]int
	scores[0] = 90
	scores[1] = 85
	fmt.Println(scores)
}

Array Literals

An array can be declared and filled in one step using a literal, and the [...] syntax tells Go to count the elements automatically instead of you specifying the length by hand.

Note: Use [...]Type{...} to let Go count the elements for you.

Example: Array Literals

markup
package main

import "fmt"

func main() {
	primes := [...]int{2, 3, 5, 7, 11}
	fmt.Println(primes, "length:", len(primes))
}

Arrays Are Copied by Value

Unlike slices, assigning a Go array to a new variable (or passing it to a function) copies every element into a brand-new array -- modifying the copy never affects the original.

Example: Arrays Are Copied by Value

markup
package main

import "fmt"

func main() {
	original := [3]int{1, 2, 3}
	copy := original
	copy[0] = 99
	fmt.Println("original:", original)
	fmt.Println("copy:", copy)
}
Common Mistakes
  1. Assuming an array can grow or shrink after creation -- Go arrays have a fixed length baked into their type.
  2. Forgetting that assigning an array to another variable copies the entire array, not a reference to the same data.
  3. Confusing arrays with slices and using [5]int and []int interchangeably -- they are different, incompatible types.
Chapter Summary
  • A Go array has a fixed length that is part of its type, e.g. [5]int.
  • Arrays are value types -- assigning or passing one copies all its elements.
  • Array length can be inferred with [...]Type{...} literal syntax.
  • In practice, slices (built on top of arrays) are used far more often than raw arrays.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.