ProgramGuru

Arrays

Start with Go Arrays

An array holds a fixed number of values of the same type. Its length is part of its type, so [3]int and [4]int are different types.

What you’ll learn

  • Explain the main purpose of go arrays.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Declare an array with a length in brackets, for example var scores [3]int. Each element initially has the zero value of its type. An array literal such as [3]int{10, 20, 30} supplies values, and [...]int{...} lets the compiler count them.

Arrays are values in Go. Assigning an array to another array of the same type copies its elements; the two arrays are then independent. For resizable sequences, Go programmers generally use slices instead.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for arraysAn array assignment copies the entire fixed-size value.[3]int literalStep 1Assign to copyStep 2Change copy[0]Step 3Original unchangedStep 4An array assignment copies the entire fixed-size value.
An array assignment copies the entire fixed-size value.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	scores := [3]int{10, 20, 30}
	duplicate := scores
	duplicate[0] = 99
	fmt.Println("Original:", scores)
	fmt.Println("Copy:", duplicate)
	fmt.Println("Length:", len(scores))
}

Output

Original: [10 20 30]
Copy: [99 20 30]
Length: 3

Trace what the program does

The array literal creates three integers. Assigning to duplicate copies the entire array. Updating duplicate[0] changes only the copy, while len(scores) remains 3 because an array has a fixed length.

Avoid common mistakes

  • An array length is part of its type; [3]int is not interchangeable with [4]int.
  • Arrays are copied on assignment, unlike the element-sharing behavior of slices.

Try it yourself

Create a [4]string array of weekdays. Assign it to another variable, change one element and compare the arrays.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What happens when one [3]int array is assigned to another?
Choose one answer. You can try again.

Answer and explanation

All three elements are copied

Correct. The array literal creates three integers.

What you should remember

You have practiced Go Arrays in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Accessing Array Elements →