Go Arrays

What is an Array?

An array is a fixed-size collection of elements of the same type. Its size is defined at declaration and cannot grow or shrink dynamically.

var names [3]string
var numbers [5]int

Initializing Arrays

You can set values directly when declaring:

Loading...
Output:

Using [...] lets Go infer the array's length based on the number of items.

Accessing Elements

Access elements using zero-based indexing:

names[0] = "Alice"
fmt.Println(names[0]) // Alice

Trying to access an index outside the range will result in a runtime error.

Default Values

Uninitialized array elements get default values based on their type:

  • int0
  • string""
  • boolfalse
var empty [3]int
fmt.Println(empty) // [0 0 0]

Length of Arrays

Use the len() function to find how many elements are in an array:

ages := [4]int{21, 30, 25, 28}
fmt.Println(len(ages)) // 4

Looping Through Arrays

Standard for loop:

Loading...
Output:

Using range loop:

Loading...
Output:

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic.